Perl - Special Variables - Tutorialspoint

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

There are some variables which have a predefined and special meaning in Perl. They are the variables that use punctuation characters after the usual ... Home CodingGround Jobs Whiteboard Tools Business Teachwithus PerlBasics Perl-Home Perl-Introduction Perl-Environment Perl-SyntaxOverview Perl-DataTypes Perl-Variables Perl-Scalars Perl-Arrays Perl-Hashes Perl-IF...ELSE Perl-Loops Perl-Operators Perl-Date&Time Perl-Subroutines Perl-References Perl-Formats Perl-FileI/O Perl-Directories Perl-ErrorHandling Perl-SpecialVariables Perl-CodingStandard Perl-RegularExpressions Perl-SendingEmail PerlAdvanced Perl-SocketProgramming Perl-ObjectOriented Perl-DatabaseAccess Perl-CGIProgramming Perl-Packages&Modules Perl-ProcessManagement Perl-EmbeddedDocumentation Perl-FunctionsReferences PerlUsefulResources Perl-QuestionsandAnswers Perl-QuickGuide Perl-UsefulResources Perl-Discussion SelectedReading UPSCIASExamsNotes Developer'sBestPractices QuestionsandAnswers EffectiveResumeWriting HRInterviewQuestions ComputerGlossary WhoisWho Perl-SpecialVariables Advertisements PreviousPage NextPage  PerlOnlineTraining 46Lectures 4.5hours DeviKillada MoreDetail COMPLETEPERLProgramming 11Lectures 1.5hours HarshitSrivastava MoreDetail PerlforBeginners:LearnAtoZofPerlScriptingHands-on 30Lectures 6hours TELCOMAGlobal MoreDetail TherearesomevariableswhichhaveapredefinedandspecialmeaninginPerl.Theyarethevariablesthatusepunctuationcharactersaftertheusualvariableindicator($,@,or%),suchas$_(explainedbelow). Mostofthespecialvariableshaveanenglishlikelongname,e.g.,OperatingSystemErrorvariable$!canbewrittenas$OS_ERROR.Butifyouaregoingtouseenglishlikenames,thenyouwouldhavetoputonelineuseEnglish;atthetopofyourprogramfile.Thisguidestheinterpretertopickupexactmeaningofthevariable. Themostcommonlyusedspecialvariableis$_,whichcontainsthedefaultinputandpattern-searchingstring.Forexample,inthefollowinglines− LiveDemo #!/usr/bin/perl foreach('hickory','dickory','doc'){ print$_; print"\n"; } Whenexecuted,thiswillproducethefollowingresult− hickory dickory doc Again,let'scheckthesameexamplewithoutusing$_variableexplicitly− LiveDemo #!/usr/bin/perl foreach('hickory','dickory','doc'){ print; print"\n"; } Whenexecuted,thiswillalsoproducethefollowingresult− hickory dickory doc Thefirsttimetheloopisexecuted,"hickory"isprinted.Thesecondtimearound,"dickory"isprinted,andthethirdtime,"doc"isprinted.That'sbecauseineachiterationoftheloop,thecurrentstringisplacedin$_,andisusedbydefaultbyprint.HerearetheplaceswherePerlwillassume$_evenifyoudon'tspecifyit− Variousunaryfunctions,includingfunctionslikeordandint,aswellastheallfiletests(-f,-d)exceptfor-t,whichdefaultstoSTDIN. Variouslistfunctionslikeprintandunlink. Thepattern-matchingoperationsm//,s///,andtr///whenusedwithoutan=~operator. Thedefaultiteratorvariableinaforeachloopifnoothervariableissupplied. Theimplicititeratorvariableinthegrepandmapfunctions. Thedefaultplacetoputaninputrecordwhenaline-inputoperation'sresultistestedbyitselfasthesolecriterionofawhiletest(i.e.,).Notethatoutsideofawhiletest,thiswillnothappen. SpecialVariableTypes Basedontheusageandnatureofspecialvariables,wecancategorizetheminthefollowingcategories− GlobalScalarSpecialVariables. GlobalArraySpecialVariables. GlobalHashSpecialVariables. GlobalSpecialFilehandles. GlobalSpecialConstants. RegularExpressionSpecialVariables. FilehandleSpecialVariables. GlobalScalarSpecialVariables Hereisthelistofallthescalarspecialvariables.Wehavelistedcorrespondingenglishlikenamesalongwiththesymbolicnames. $_ Thedefaultinputandpattern-searchingspace. $ARG $. Thecurrentinputlinenumberofthelastfilehandlethatwasread.Anexplicitcloseonthefilehandleresetsthelinenumber. $NR $/ Theinputrecordseparator;newlinebydefault.Ifsettothenullstring,ittreatsblanklinesasdelimiters. $RS $, Theoutputfieldseparatorfortheprintoperator. $OFS $\ Theoutputrecordseparatorfortheprintoperator. $ORS $" Like"$,"exceptthatitappliestolistvaluesinterpolatedintoadouble-quotedstring(orsimilarinterpretedstring).Defaultisaspace. $LIST_SEPARATOR $; Thesubscriptseparatorformultidimensionalarrayemulation.Defaultis"\034". $SUBSCRIPT_SEPARATOR $^L Whataformatoutputstoperformaformfeed.Defaultis"\f". $FORMAT_FORMFEED $: Thecurrentsetofcharactersafterwhichastringmaybebrokentofillcontinuationfields(startingwith^)inaformat.Defaultis"\n"". $FORMAT_LINE_BREAK_CHARACTERS $^A Thecurrentvalueofthewriteaccumulatorforformatlines. $ACCUMULATOR $# Containstheoutputformatforprintednumbers(deprecated). $OFMT $? Thestatusreturnedbythelastpipeclose,backtick(``)command,orsystemoperator. $CHILD_ERROR $! Ifusedinanumericcontext,yieldsthecurrentvalueoftheerrnovariable,identifyingthelastsystemcallerror.Ifusedinastringcontext,yieldsthecorrespondingsystemerrorstring. $OS_ERRORor$ERRNO $@ ThePerlsyntaxerrormessagefromthelastevalcommand. $EVAL_ERROR $$ ThepidofthePerlprocessrunningthisscript. $PROCESS_IDor$PID $< TherealuserID(uid)ofthisprocess. $REAL_USER_IDor$UID $> TheeffectiveuserIDofthisprocess. $EFFECTIVE_USER_IDor$EUID $( TherealgroupID(gid)ofthisprocess. $REAL_GROUP_IDor$GID $) Theeffectivegidofthisprocess. $EFFECTIVE_GROUP_IDor$EGID $0 ContainsthenameofthefilecontainingthePerlscriptbeingexecuted. $PROGRAM_NAME $[ Theindexofthefirstelementinanarrayandofthefirstcharacterinasubstring.Defaultis0. $] Returnstheversionpluspatchleveldividedby1000. $PERL_VERSION $^D Thecurrentvalueofthedebuggingflags. $DEBUGGING $^E Extendederrormessageonsomeplatforms. $EXTENDED_OS_ERROR $^F Themaximumsystemfiledescriptor,ordinarily2. $SYSTEM_FD_MAX $^H Containsinternalcompilerhintsenabledbycertainpragmaticmodules. $^I Thecurrentvalueoftheinplace-editextension.Useundeftodisableinplaceediting. $INPLACE_EDIT $^M Thecontentsof$McanbeusedasanemergencymemorypoolincasePerldieswithanout-of-memoryerror.Useof$MrequiresaspecialcompilationofPerl.SeetheINSTALLdocumentformoreinformation. $^O ContainsthenameoftheoperatingsystemthatthecurrentPerlbinarywascompiledfor. $OSNAME $^P Theinternalflagthatthedebuggerclearssothatitdoesn'tdebugitself. $PERLDB $^T Thetimeatwhichthescriptbeganrunning,insecondssincetheepoch. $BASETIME $^W Thecurrentvalueofthewarningswitch,eithertrueorfalse. $WARNING $^X ThenamethatthePerlbinaryitselfwasexecutedas. $EXECUTABLE_NAME $ARGV Containsthenameofthecurrentfilewhenreadingfrom. GlobalArraySpecialVariables @ARGV Thearraycontainingthecommand-lineargumentsintendedforthescript. @INC ThearraycontainingthelistofplacestolookforPerlscriptstobeevaluatedbythedo,require,oruseconstructs. @F Thearrayintowhichtheinputlinesaresplitwhenthe-acommand-lineswitchisgiven. GlobalHashSpecialVariables %INC Thehashcontainingentriesforthefilenameofeachfilethathasbeenincludedviadoorrequire. %ENV Thehashcontainingyourcurrentenvironment. %SIG Thehashusedtosetsignalhandlersforvarioussignals. GlobalSpecialFilehandles ARGV Thespecialfilehandlethatiteratesovercommandlinefilenamesin@ARGV.Usuallywrittenasthenullfilehandlein<>. STDERR Thespecialfilehandleforstandarderrorinanypackage. STDIN Thespecialfilehandleforstandardinputinanypackage. STDOUT Thespecialfilehandleforstandardoutputinanypackage. DATA Thespecialfilehandlethatreferstoanythingfollowingthe__END__tokeninthefilecontainingthescript.Or,thespecialfilehandleforanythingfollowingthe__DATA__tokeninarequiredfile,aslongasyou'rereadingdatainthesamepackage__DATA__wasfoundin. _(underscore) Thespecialfilehandleusedtocachetheinformationfromthelaststat,lstat,orfiletestoperator. GlobalSpecialConstants __END__ Indicatesthelogicalendofyourprogram.Anyfollowingtextisignored,butmaybereadviatheDATAfilehandle. __FILE__ Representsthefilenameatthepointinyourprogramwhereit'sused.Notinterpolatedintostrings. __LINE__ Representsthecurrentlinenumber.Notinterpolatedintostrings. __PACKAGE__ Representsthecurrentpackagenameatcompiletime,orundefinedifthereisnocurrentpackage.Notinterpolatedintostrings. RegularExpressionSpecialVariables $digit Containsthetextmatchedbythecorrespondingsetofparenthesesinthelastpatternmatched.Forexample,$1matcheswhateverwascontainedinthefirstsetofparenthesesinthepreviousregularexpression. $& Thestringmatchedbythelastsuccessfulpatternmatch. $MATCH $` Thestringprecedingwhateverwasmatchedbythelastsuccessfulpatternmatch. $PREMATCH $' Thestringfollowingwhateverwasmatchedbythelastsuccessfulpatternmatch. $POSTMATCH $+ Thelastbracketmatchedbythelastsearchpattern.Thisisusefulifyoudon'tknowwhichofasetofalternativepatternswasmatched.Forexample:/Version:(.*)|Revision:(.*)/&&($rev=$+); $LAST_PAREN_MATCH FilehandleSpecialVariables $| Ifsettononzero,forcesanfflush(3)aftereverywriteorprintonthecurrentlyselectedoutputchannel. $OUTPUT_AUTOFLUSH $% Thecurrentpagenumberofthecurrentlyselectedoutputchannel. $FORMAT_PAGE_NUMBER $= Thecurrentpagelength(printablelines)ofthecurrentlyselectedoutputchannel.Defaultis60. $FORMAT_LINES_PER_PAGE $- Thenumberoflinesleftonthepageofthecurrentlyselectedoutputchannel. $FORMAT_LINES_LEFT $~ Thenameofthecurrentreportformatforthecurrentlyselectedoutputchannel.Defaultisthenameofthefilehandle. $FORMAT_NAME $^ Thenameofthecurrenttop-of-pageformatforthecurrentlyselectedoutputchannel.Defaultisthenameofthefilehandlewith_TOPappended. $FORMAT_TOP_NAME PreviousPage PrintPage NextPage  Advertisements



請為這篇文章評分?