Special Variables - Perl in a Nutshell [Book] - O'Reilly

文章推薦指數: 80 %
投票人數:10人

Some variables have a predefined and special meaning in Perl. They are the variables that use punctuation characters after the usual variable indicator ( $ ... Skiptomaincontent PerlinaNutshellby GetfullaccesstoPerlinaNutshelland60K+othertitles,withfree10-daytrialofO'Reilly. There'salsoliveonlineevents,interactivecontent,certificationprepmaterials,andmore. Startyourfreetrial SpecialVariables Somevariableshaveapredefined andspecialmeaninginPerl.Theyarethevariables thatusepunctuationcharacters aftertheusualvariableindicator($,@,or %),suchas$_. Theexplicit,long-formnamesshownarethevariables’equivalents whenyouusetheEnglishmodulebyincluding "useEnglish;"atthetopofyourprogram.GlobalSpecialVariables Themostcommonlyusedspecialvariableis$_,whichcontains thedefaultinputandpattern-searchingstring. Forexample,inthefollowinglines: foreach('hickory','dickory','doc'){ print; } Thefirsttimetheloopisexecuted,“hickory”isprinted. Thesecondtimearound,“dickory”isprinted,andthethirdtime,“doc” isprinted.That’sbecauseineachiterationoftheloop, thecurrentstringisplaced in$_,andisusedbydefaultbyprint. HerearetheplaceswherePerlwillassume$_evenifyoudon’t specifyit:Variousunaryfunctions,includingfunctionslikeordand int,aswellastheallfiletests(-f,-d)exceptfor -t,whichdefaultstoSTDIN.Variouslistfunctionslikeprintandunlink.Thepattern-matchingoperationsm//,s///,andtr/// whenusedwithoutan=~operator.Thedefaultiteratorvariableinaforeachloopifnoother variableissupplied.Theimplicititeratorvariableinthegrepandmap functions.Thedefaultplacetoputaninputrecordwhenaline-inputoperation’s resultistestedbyitselfasthesolecriterionofa whiletest(i.e.,). Notethatoutsideofawhiletest,this willnothappen.Thefollowingisacompletelistingofglobalspecialvariables: $_ , $ARG Thedefaultinputandpattern-searchingspace. $. , $INPUT_LINE_NUMBER $NR Thecurrentinputlinenumberofthelastfilehandlethatwasread.An explicitcloseonthefilehandleresetsthelinenumber. $/ , $INPUT_RECORD_SEPARATOR $RS Theinputrecordseparator;newlinebydefault. Ifsettothenullstring,ittreatsblanklinesas delimiters. $, , $OUTPUT_FIELD_SEPARATOR $OFS Theoutputfieldseparatorfortheprintoperator. $\ , $OUTPUT_RECORD_SEPARATOR , $ORS Theoutputrecordseparatorfortheprintoperator. $ , $LIST_SEPARATOR Like"$,"exceptthatitappliestolistvaluesinterpolated intoadouble-quotedstring(orsimilarinterpretedstring).Default isaspace. $; , $SUBSCRIPT_SEPARATOR , $SUBSEP Thesubscriptseparatorformultidimensionalarrayemulation. Defaultis"\034". $^L , $FORMAT_FORMFEED Whataformatoutputstoperformaformfeed.Defaultis"\f". $: , $FORMAT_LINE_BREAK_CHARACTERS Thecurrentsetofcharactersafterwhichastringmaybebrokentofill continuationfields(startingwith^)inaformat. Defaultis"\n"". $^A , $ACCUMULATOR Thecurrentvalueofthewrite accumulatorforformatlines. $# , $OFMT Containstheoutputformatforprintednumbers (deprecated). $? , $CHILD_ERROR Thestatusreturnedbythelastpipeclose,backtick(``)command, orsystemoperator. $! , $OS_ERROR , $ERRNO Ifusedinanumericcontext,yieldsthecurrentvalueofthe errnovariable,identifyingthelastsystemcallerror. Ifusedinastringcontext, yieldsthecorrespondingsystemerrorstring. $@ , $EVAL_ERROR ThePerlsyntaxerrormessagefromthelastevalcommand. $$ , $PROCESS_ID , $PID ThepidofthePerlprocessrunningthisscript. $< , $REAL_USER_ID , $UID TherealuserID(uid)ofthisprocess. $> , $EFFECTIVE_USER_ID , $EUID Theeffectiveuidofthisprocess. $( , $REAL_GROUP_ID , $GID TherealgroupID(gid)ofthisprocess. $) , $EFFECTIVE_GROUP_ID , $EGID Theeffectivegidofthisprocess. $0 , $PROGRAM_NAME ContainsthenameofthefilecontainingthePerlscriptbeingexecuted. $[ Theindexofthefirstelementinanarrayandofthefirstcharacterin asubstring.Defaultis0. $] , $PERL_VERSION Returnstheversionpluspatchleveldividedby1000. $^D , $DEBUGGING Thecurrentvalueofthedebuggingflags. $^E , $EXTENDED_OS_ERROR Extendederrormessageonsomeplatforms. $^F , $SYSTEM_FD_MAX Themaximumsystemfiledescriptor,ordinarily2. $^H Containsinternalcompilerhintsenabledbycertain pragmaticmodules. $^I , $INPLACE_EDIT Thecurrentvalueoftheinplace-editextension.Useundeftodisable inplaceediting. $^M Thecontentsof$Mcanbeusedasanemergencymemorypoolin casePerldieswithanout-of-memoryerror.Useof$M requiresaspecialcompilationofPerl.SeetheINSTALLdocumentfor moreinformation. $^O , $OSNAME Containsthenameoftheoperatingsystemthatthecurrent Perlbinarywascompiledfor. $^P , $PERLDB Theinternalflagthatthedebuggerclearssothatitdoesn’tdebug itself. $^T , $BASETIME Thetimeatwhichthescriptbeganrunning,insecondssincetheepoch. $^W , $WARNING Thecurrentvalueofthewarningswitch,eithertrueor false. $^X , $EXECUTABLE_NAME ThenamethatthePerlbinaryitselfwasexecutedas. $ARGV Containsthenameofthecurrentfilewhenreadingfrom.GlobalSpecialArraysandHashes @ARGV Thearraycontainingthecommand-lineargumentsintendedforthe script. @INC ThearraycontainingthelistofplacestolookforPerlscripts tobeevaluatedbythedo,require,oruse constructs. @F Thearrayintowhichtheinputlinesaresplitwhenthe-a command-lineswitchisgiven. %INC Thehashcontainingentriesforthefilenameofeachfilethathasbeen includedviadoorrequire. %ENV Thehashcontainingyourcurrentenvironment. %SIG Thehashusedtosetsignalhandlersforvarioussignals.GlobalSpecialFilehandles ARGV Thespecialfilehandlethatiteratesovercommandlinefilenamesin @ARGV.Usuallywrittenasthenullfilehandlein<>. STDERR Thespecialfilehandleforstandarderrorinanypackage. STDIN Thespecialfilehandleforstandardinputinanypackage. STDOUT Thespecialfilehandleforstandardoutputinanypackage. DATA Thespecialfilehandlethatreferstoanythingfollowingthe __END__tokeninthefile containingthescript.Or,thespecialfilehandleforanything followingthe__DATA__tokeninarequiredfile,aslongas you’rereadingdatainthesamepackage__DATA__was foundin. _(underscore) Thespecialfilehandleusedtocachetheinformationfromthelaststat, lstat,orfiletestoperator.GlobalSpecialConstants __END__ Indicatesthelogicalendofyourprogram.Anyfollowingtextisignored, butmaybereadviatheDATAfilehandle. __FILE__ Representsthefilenameatthepointinyourprogramwhereit’sused.Not interpolatedintostrings. __LINE__ Representsthecurrentlinenumber.Notinterpolatedintostrings. __PACKAGE__ Representsthecurrentpackagenameatcompiletime,orundefinedifthere isnocurrentpackage.Notinterpolatedintostrings.RegularExpressionSpecialVariables Formoreinformationonregularexpressions, seeSection4.6laterinthischapter. $ digit Containsthetextmatchedbythecorrespondingsetofparenthesesin thelastpatternmatched.Forexample,$1matcheswhateverwascontained inthefirstsetofparenthesesinthepreviousregularexpression. $& , $MATCH Thestringmatchedbythelastsuccessfulpatternmatch. $` , $PREMATCH Thestringprecedingwhateverwasmatchedbythelastsuccessfulpattern match. $' , $POSTMATCH Thestringfollowingwhateverwasmatchedbythelastsuccessfulpattern match. $+ , $LAST_PAREN_MATCH Thelastbracketmatchedbythelastsearchpattern.Thisisusefulifyou don’tknowwhichofasetofalternativepatternswasmatched.Forexample: /Version:(.*)|Revision:(.*)/&&($rev=$+); FilehandleSpecialVariables Mostofthesevariablesonlyapplywhenusingformats. SeeSection4.10laterinthischapter. $| $OUTPUT_AUTOFLUSH Ifsettononzero,forcesanfflush(3)aftereverywriteor printonthecurrentlyselectedoutputchannel. $% $FORMAT_PAGE_NUMBER Thecurrentpagenumberofthecurrentlyselectedoutputchannel. $= $FORMAT_LINES_PER_PAGE Thecurrentpagelength(printablelines)ofthecurrentlyselectedoutput channel.Defaultis60. $- $FORMAT_LINES_LEFT Thenumberoflinesleftonthepageofthecurrentlyselectedoutput channel. $~ $FORMAT_NAME Thenameofthecurrentreportformatforthecurrentlyselectedoutput channel.Defaultisthenameofthefilehandle. $^ $FORMAT_TOP_NAME Thenameofthecurrenttop-of-pageformatforthecurrentlyselected outputchannel.Defaultisthenameofthefilehandle with_TOPappended. GetPerlinaNutshellnowwiththeO’Reillylearningplatform. O’Reillymembersexperienceliveonlinetraining,plusbooks,videos,anddigitalcontentfromnearly200publishers. Startyourfreetrial Don’tleaveempty-handed GetMarkRichards’sSoftwareArchitecturePatternsebooktobetterunderstandhowtodesigncomponents—andhowtheyshouldinteract. It’syours,free. Getitnow Close



請為這篇文章評分?