SPECIAL VARIABLES. The following names have special meaning to Perl. Most punctuation names have reasonable mnemonics, or analogs in the shells. Nevertheless, ...
PerldocBrowser
5.36.0
Latest
5.36.0
5.34.1
5.34.0
5.32.1
5.32.0
5.30.3
5.30.2
5.30.1
5.30.0
5.28.3
5.28.2
5.28.1
5.28.0
5.26.3
5.26.2
5.26.1
5.26.0
5.24.4
5.24.3
5.24.2
5.24.1
5.24.0
5.22.4
5.22.3
5.22.2
5.22.1
5.22.0
5.20.3
5.20.2
5.20.1
5.20.0
5.18.4
5.18.3
5.18.2
5.18.1
5.18.0
5.16.3
5.16.2
5.16.1
5.16.0
5.14.4
5.14.3
5.14.2
5.14.1
5.14.0
5.12.5
5.12.4
5.12.3
5.12.2
5.12.1
5.12.0
5.10.1
5.10.0
5.8.9
5.8.8
5.8.7
5.8.6
5.8.5
5.8.4
5.8.3
5.8.2
5.8.1
5.8.0
5.6.2
5.6.1
5.6.0
5.005_04
5.005_03
5.005_02
5.005_01
5.005
Dev
blead
5.37.4
5.37.3
5.37.2
5.37.1
5.37.0
5.36.0-RC3
5.36.0-RC2
5.35.11
5.35.10
5.35.9
5.35.8
5.35.7
5.35.6
5.35.5
5.35.4
5.35.3
5.35.2
5.35.1
5.35.0
5.33.9
5.33.8
5.33.7
5.33.6
5.33.5
5.33.4
5.33.3
5.33.2
5.33.1
5.33.0
Documentation
Perl
Intro
Tutorials
FAQs
Reference
Operators
Functions
Variables
Modules
Utilities
Community
History
Expand
perlvar
(source,
CPAN)
CONTENTS
NAME
DESCRIPTION
TheSyntaxofVariableNames
SPECIALVARIABLES
GeneralVariables
Variablesrelatedtoregularexpressions
Performanceissues
Variablesrelatedtofilehandles
Variablesrelatedtoformats
ErrorVariables
Variablesrelatedtotheinterpreterstate
Deprecatedandremovedvariables
#NAME
perlvar-Perlpredefinedvariables
#DESCRIPTION
#TheSyntaxofVariableNames
VariablenamesinPerlcanhaveseveralformats.Usually,theymustbeginwithaletterorunderscore,inwhichcasetheycanbearbitrarilylong(uptoaninternallimitof251characters)andmaycontainletters,digits,underscores,orthespecialsequence::or'.Inthiscase,thepartbeforethelast::or'istakentobeapackagequalifier;seeperlmod.AUnicodeletterthatisnotASCIIisnotconsideredtobealetterunless"useutf8"isineffect,andsomewhatmorecomplicatedrulesapply;see"Identifierparsing"inperldatafordetails.
Perlvariablenamesmayalsobeasequenceofdigits,asinglepunctuationcharacter,orthetwo-charactersequence:^(caretorCIRCUMFLEXACCENT)followedbyanyoneofthecharacters[][A-Z^_?\].ThesenamesareallreservedforspecialusesbyPerl;forexample,theall-digitsnamesareusedtoholddatacapturedbybackreferencesafteraregularexpressionmatch.
SincePerlv5.6.0,Perlvariablenamesmayalsobealphanumericstringsprecededbyacaret.Thesemustallbewrittenusingthedemarcatedvariableformusingcurlybracessuchas${^Foo};thebracesarenotoptional.${^Foo}denotesthescalarvariablewhosenameisconsideredtobeacontrol-Ffollowedbytwoo's.(See"Demarcatedvariablenamesusingbraces"inperldataformoreinformationonthisformofspellingavariablenameorspecifyingaccesstoanelementofanarrayorahash).ThesevariablesarereservedforfuturespecialusesbyPerl,exceptfortheonesthatbeginwith^_(caret-underscore).Nonamethatbeginswith^_willacquireaspecialmeaninginanyfutureversionofPerl;suchnamesmaythereforebeusedsafelyinprograms.$^_itself,however,isreserved.
Notethatyoualsomustusethedemarcatedformtoaccesssubscriptsofvariablesofthistypewheninterpolating,forinstancetoaccessthefirstelementofthe@{^CAPTURE}variableinsideofadoublequotedstringyouwouldwrite"${^CAPTURE[0]}"andNOT"${^CAPTURE}[0]"whichwouldmeantoreferenceascalarvariablenamed${^CAPTURE}andnotindex0ofthemagic@{^CAPTURE}arraywhichispopulatedbytheregexengine.
Perlidentifiersthatbeginwithdigitsorpunctuationcharactersareexemptfromtheeffectsofthepackagedeclarationandarealwaysforcedtobeinpackagemain;theyarealsoexemptfromstrict'vars'errors.Afewothernamesarealsoexemptintheseways:
ENVSTDIN
INCSTDOUT
ARGVSTDERR
ARGVOUT
SIG
Inparticular,thespecial${^_XYZ}variablesarealwaystakentobeinpackagemain,regardlessofanypackagedeclarationspresentlyinscope.
#SPECIALVARIABLES
ThefollowingnameshavespecialmeaningtoPerl.Mostpunctuationnameshavereasonablemnemonics,oranalogsintheshells.Nevertheless,ifyouwishtouselongvariablenames,youneedonlysay:
useEnglish;
atthetopofyourprogram.Thisaliasesalltheshortnamestothelongnamesinthecurrentpackage.Someevenhavemediumnames,generallyborrowedfromawk.Formoreinfo,pleaseseeEnglish.
Beforeyoucontinue,notethesortorderforvariables.Ingeneral,wefirstlistthevariablesincase-insensitive,almost-lexigraphicalorder(ignoringthe{or^precedingwords,asin${^UNICODE}or$^T),although$_and@_moveuptothetopofthepile.Forvariableswiththesameidentifier,welistitinorderofscalar,array,hash,andbareword.
#GeneralVariables
#$ARG
#$_
Thedefaultinputandpattern-searchingspace.Thefollowingpairsareequivalent:
while(<>){...}#equivalentonlyinwhile!
while(defined($_=<>)){...}
/^Subject:/
$_=~/^Subject:/
tr/a-z/A-Z/
$_=~tr/a-z/A-Z/
chomp
chomp($_)
HerearetheplaceswherePerlwillassume$_evenifyoudon'tuseit:
Thefollowingfunctionsuse$_asadefaultargument:
abs,alarm,chomp,chop,chr,chroot,cos,defined,eval,evalbytes,exp,fc,glob,hex,int,lc,lcfirst,length,log,lstat,mkdir,oct,ord,pos,print,printf,quotemeta,readlink,readpipe,ref,require,reverse(inscalarcontextonly),rmdir,say,sin,split(foritssecondargument),sqrt,stat,study,uc,ucfirst,unlink,unpack.
Allfiletests(-f,-d)exceptfor-t,whichdefaultstoSTDIN.See"-X"inperlfunc
Thepatternmatchingoperationsm//,s///andtr///(akay///)whenusedwithoutan=~operator.
Thedefaultiteratorvariableinaforeachloopifnoothervariableissupplied.
Theimplicititeratorvariableinthegrep()andmap()functions.
Theimplicitvariableofgiven().
Thedefaultplacetoputthenextvalueorinputrecordwhena,readline,readdiroreachoperation'sresultistestedbyitselfasthesolecriterionofawhiletest.Outsideawhiletest,thiswillnothappen.
$_isaglobalvariable.
However,betweenperlv5.10.0andv5.24.0,itcouldbeusedlexicallybywritingmy$_.Making$_refertotheglobal$_inthesamescopewasthenpossiblewithour$_.Thisexperimentalfeaturewasremovedandisnowafatalerror,butyoumayencounteritinoldercode.
Mnemonic:underlineisunderstoodincertainoperations.
#@ARG
#@_
Withinasubroutinethearray@_containstheparameterspassedtothatsubroutine.Insideasubroutine,@_isthedefaultarrayforthearrayoperatorspopandshift.
Seeperlsub.
#$LIST_SEPARATOR
#$"
Whenanarrayoranarraysliceisinterpolatedintoadouble-quotedstringorasimilarcontextsuchas/.../,itselementsareseparatedbythisvalue.Defaultisaspace.Forexample,this:
print"Thearrayis:@array\n";
isequivalenttothis:
print"Thearrayis:".join($",@array)."\n";
Mnemonic:worksindouble-quotedcontext.
#$PROCESS_ID
#$PID
#$$
TheprocessnumberofthePerlrunningthisscript.Thoughyoucansetthisvariable,doingsoisgenerallydiscouraged,althoughitcanbeinvaluableforsometestingpurposes.Itwillberesetautomaticallyacrossfork()calls.
NoteforLinuxandDebianGNU/kFreeBSDusers:BeforePerlv5.16.0perlwouldemulatePOSIXsemanticsonLinuxsystemsusingLinuxThreads,apartialimplementationofPOSIXThreadsthathassincebeensupersededbytheNativePOSIXThreadLibrary(NPTL).
LinuxThreadsisnowobsoleteonLinux,andcachinggetpid()likethismadeembeddingperlunnecessarilycomplex(sinceyou'dhavetomanuallyupdatethevalueof$$),sonow$$andgetppid()willalwaysreturnthesamevaluesastheunderlyingClibrary.
DebianGNU/kFreeBSDsystemsalsousedLinuxThreadsupuntilandincludingthe6.0release,butafterthatmovedtoFreeBSDthreadsemantics,whicharePOSIX-like.
ToseeifyoursystemisaffectedbythisdiscrepancycheckifgetconfGNU_LIBPTHREAD_VERSION|grep-qNPTLreturnsafalsevalue.NTPLthreadspreservethePOSIXsemantics.
Mnemonic:sameasshells.
#$PROGRAM_NAME
#$0
Containsthenameoftheprogrambeingexecuted.
Onsome(butnotall)operatingsystemsassigningto$0modifiestheargumentareathatthepsprogramsees.Onsomeplatformsyoumayhavetousespecialpsoptionsoradifferentpstoseethechanges.Modifyingthe$0ismoreusefulasawayofindicatingthecurrentprogramstatethanitisforhidingtheprogramyou'rerunning.
Notethatthereareplatform-specificlimitationsonthemaximumlengthof$0.Inthemostextremecaseitmaybelimitedtothespaceoccupiedbytheoriginal$0.
Insomeplatformstheremaybearbitraryamountofpadding,forexamplespacecharacters,afterthemodifiednameasshownbyps.Insomeplatformsthispaddingmayextendallthewaytotheoriginallengthoftheargumentarea,nomatterwhatyoudo(thisisthecaseforexamplewithLinux2.2).
NoteforBSDusers:setting$0doesnotcompletelyremove"perl"fromtheps(1)output.Forexample,setting$0to"foobar"mayresultin"perl:foobar(perl)"(whetherboththe"perl:"prefixandthe"(perl)"suffixareshowndependsonyourexactBSDvariantandversion).Thisisanoperatingsystemfeature,Perlcannothelpit.
InmultithreadedscriptsPerlcoordinatesthethreadssothatanythreadmaymodifyitscopyofthe$0andthechangebecomesvisibletops(1)(assumingtheoperatingsystemplaysalong).Notethattheviewof$0theotherthreadshavewillnotchangesincetheyhavetheirowncopiesofit.
Iftheprogramhasbeengiventoperlviatheswitches-eor-E,$0willcontainthestring"-e".
OnLinuxasofperlv5.14.0thelegacyprocessnamewillbesetwithprctl(2),inadditiontoalteringthePOSIXnameviaargv[0]asperlhasdonesinceversion4.000.Nowsystemutilitiesthatreadthelegacyprocessnamesuchasps,topandkillallwillrecognizethenameyousetwhenassigningto$0.Thestringyousupplywillbecutoffat16bytes,thisisalimitationimposedbyLinux.
Widecharactersareinvalidin$0values.Forhistoricalreasons,though,PerlacceptsthemandencodesthemtoUTF-8.Whenthishappensawide-characterwarningistriggered.
Mnemonic:sameasshandksh.
#$REAL_GROUP_ID
#$GID
#$(
Therealgidofthisprocess.Ifyouareonamachinethatsupportsmembershipinmultiplegroupssimultaneously,givesaspaceseparatedlistofgroupsyouarein.Thefirstnumberistheonereturnedbygetgid(),andthesubsequentonesbygetgroups(),oneofwhichmaybethesameasthefirstnumber.
However,avalueassignedto$(mustbeasinglenumberusedtosettherealgid.Sothevaluegivenby$(shouldnotbeassignedbackto$(withoutbeingforcednumeric,suchasbyaddingzero.Notethatthisisdifferenttotheeffectivegid($))whichdoestakealist.
YoucanchangeboththerealgidandtheeffectivegidatthesametimebyusingPOSIX::setgid().Changesto$(requireacheckto$!todetectanypossibleerrorsafteranattemptedchange.
Mnemonic:parenthesesareusedtogroupthings.Therealgidisthegroupyouleft,ifyou'rerunningsetgid.
#$EFFECTIVE_GROUP_ID
#$EGID
#$)
Theeffectivegidofthisprocess.Ifyouareonamachinethatsupportsmembershipinmultiplegroupssimultaneously,givesaspaceseparatedlistofgroupsyouarein.Thefirstnumberistheonereturnedbygetegid(),andthesubsequentonesbygetgroups(),oneofwhichmaybethesameasthefirstnumber.
Similarly,avalueassignedto$)mustalsobeaspace-separatedlistofnumbers.Thefirstnumbersetstheeffectivegid,andtherest(ifany)arepassedtosetgroups().Togettheeffectofanemptylistforsetgroups(),justrepeattheneweffectivegid;thatis,toforceaneffectivegidof5andaneffectivelyemptysetgroups()list,say$)="55".
YoucanchangeboththeeffectivegidandtherealgidatthesametimebyusingPOSIX::setgid()(useonlyasinglenumericargument).Changesto$)requireacheckto$!todetectanypossibleerrorsafteranattemptedchange.
$,$(and$)canbesetonlyonmachinesthatsupportthecorrespondingset[re][ug]id()routine.$(and$)canbeswappedonlyonmachinessupportingsetregid().
Mnemonic:parenthesesareusedtogroupthings.Theeffectivegidisthegroupthat'srightforyou,ifyou'rerunningsetgid.
#$REAL_USER_ID
#$UID
#$<
Therealuidofthisprocess.YoucanchangeboththerealuidandtheeffectiveuidatthesametimebyusingPOSIX::setuid().Sincechangesto$
Theeffectiveuidofthisprocess.Forexample:
$<=$>;#setrealtoeffectiveuid
($)=($>,$requireacheckto$!todetectanypossibleerrorsafteranattemptedchange.
$canbeswappedonlyonmachinessupportingsetreuid().
Mnemonic:it'stheuidyouwentto,ifyou'rerunningsetuid.
#$SUBSCRIPT_SEPARATOR
#$SUBSEP
#$;
Thesubscriptseparatorformultidimensionalarrayemulation.Ifyourefertoahashelementas
$foo{$x,$y,$z}
itreallymeans
$foo{join($;,$x,$y,$z)}
Butdon'tput
@foo{$x,$y,$z}#aslice--notethe@
whichmeans
($foo{$x},$foo{$y},$foo{$z})
Defaultis"\034",thesameasSUBSEPinawk.Ifyourkeyscontainbinarydatatheremightnotbeanysafevaluefor$;.
Considerusing"real"multidimensionalarraysasdescribedinperllol.
Mnemonic:comma(thesyntacticsubscriptseparator)isasemi-semicolon.
#$a
#$b
Specialpackagevariableswhenusingsort(),see"sort"inperlfunc.Becauseofthisspecialness$aand$bdon'tneedtobedeclared(usingusevars,orour())evenwhenusingthestrict'vars'pragma.Don'tlexicalizethemwithmy$aormy$bifyouwanttobeabletousetheminthesort()comparisonblockorfunction.
#%ENV
Thehash%ENVcontainsyourcurrentenvironment.SettingavalueinENVchangestheenvironmentforanychildprocessesyousubsequentlyfork()off.
Asofv5.18.0,bothkeysandvaluesstoredin%ENVarestringified.
my$foo=1;
$ENV{'bar'}=\$foo;
if(ref$ENV{'bar'}){
say"Pre5.18.0Behaviour";
}else{
say"Post5.18.0Behaviour";
}
Previously,onlychildprocessesreceivedstringifiedvalues:
my$foo=1;
$ENV{'bar'}=\$foo;
#Alwaysprinted'nonref'
system($^X,'-e',
q/print(ref$ENV{'bar'}?'ref':'nonref')/);
Thishappensbecauseyoucan'treallysharearbitrarydatastructureswithforeignprocesses.
#$OLD_PERL_VERSION
#$]
Therevision,version,andsubversionofthePerlinterpreter,representedasadecimaloftheform5.XXXYYY,whereXXXistheversion/1e3andYYYisthesubversion/1e6.Forexample,Perlv5.10.1wouldbe"5.010001".
ThisvariablecanbeusedtodeterminewhetherthePerlinterpreterexecutingascriptisintherightrangeofversions:
warn"NoPerlIO!\n"if"$]"<5.008;
Whencomparing$],numericcomparisonoperatorsshouldbeused,butthevariableshouldbestringifiedfirsttoavoidissueswhereitsoriginalnumericvalueisinaccurate.
SeealsothedocumentationofuseVERSIONandrequireVERSIONforaconvenientwaytofailiftherunningPerlinterpreteristooold.
See"$^V"forarepresentationofthePerlversionasaversionobject,whichallowsmoreflexiblestringcomparisons.
Themainadvantageof$]over$^VisthatitworksthesameonanyversionofPerl.Thedisadvantagesarethatitcan'teasilybecomparedtoversionsinotherformats(e.g.literalv-strings,"v1.2.3"orversionobjects)andnumericcomparisonsaresubjecttothebinaryfloatingpointrepresentation;it'sgoodfornumericliteralversionchecksandbadforcomparingtoavariablethathasn'tbeensanity-checked.
The$OLD_PERL_VERSIONformwasaddedinPerlv5.20.0forhistoricalreasonsbutitsuseisdiscouraged.(Ifyourreasontouse$]istoruncodeonoldperlsthenreferringtoitas$OLD_PERL_VERSIONwouldbeself-defeating.)
Mnemonic:Isthisversionofperlintherightbracket?
#$SYSTEM_FD_MAX
#$^F
Themaximumsystemfiledescriptor,ordinarily2.Systemfiledescriptorsarepassedtoexec()edprocesses,whilehigherfiledescriptorsarenot.Also,duringanopen(),systemfiledescriptorsarepreservedeveniftheopen()fails(ordinaryfiledescriptorsareclosedbeforetheopen()isattempted).Theclose-on-execstatusofafiledescriptorwillbedecidedaccordingtothevalueof$^Fwhenthecorrespondingfile,pipe,orsocketwasopened,notthetimeoftheexec().
#@F
Thearray@Fcontainsthefieldsofeachlinereadinwhenautosplitmodeisturnedon.Seeperlrunforthe-aswitch.Thisarrayispackage-specific,andmustbedeclaredorgivenafullpackagenameifnotinpackagemainwhenrunningunderstrict'vars'.
#@INC
Thearray@INCcontainsthelistofplacesthatthedoEXPR,require,oruseconstructslookfortheirlibraryfiles.Itinitiallyconsistsoftheargumentstoany-Icommand-lineswitches,followedbythedefaultPerllibrary,probably/usr/local/lib/perl.PriortoPerl5.26,.-whichrepresentsthecurrentdirectory,wasincludedin@INC;ithasbeenremoved.ThischangeinbehaviorisdocumentedinPERL_USE_UNSAFE_INCanditisnotrecommendedthat.bere-addedto@INC.Ifyouneedtomodify@INCatruntime,youshouldusetheuselibpragmatogetthemachine-dependentlibraryproperlyloadedaswell:
uselib'/mypath/libdir/';
useSomeMod;
YoucanalsoinserthooksintothefileinclusionsystembyputtingPerlcodedirectlyinto@INC.Thosehooksmaybesubroutinereferences,arrayreferencesorblessedobjects.See"require"inperlfuncfordetails.
#%INC
Thehash%INCcontainsentriesforeachfilenameincludedviathedo,require,oruseoperators.Thekeyisthefilenameyouspecified(withmodulenamesconvertedtopathnames),andthevalueisthelocationofthefilefound.Therequireoperatorusesthishashtodeterminewhetheraparticularfilehasalreadybeenincluded.
Ifthefilewasloadedviaahook(e.g.asubroutinereference,see"require"inperlfuncforadescriptionofthesehooks),thishookisbydefaultinsertedinto%INCinplaceofafilename.Note,however,thatthehookmayhavesetthe%INCentrybyitselftoprovidesomemorespecificinfo.
#$INPLACE_EDIT
#$^I
Thecurrentvalueoftheinplace-editextension.Useundeftodisableinplaceediting.
Mnemonic:valueof-iswitch.
#@ISA
Eachpackagecontainsaspecialarraycalled@ISAwhichcontainsalistofthatclass'sparentclasses,ifany.Thisarrayissimplyalistofscalars,eachofwhichisastringthatcorrespondstoapackagename.ThearrayisexaminedwhenPerldoesmethodresolution,whichiscoveredinperlobj.
Toloadpackageswhileaddingthemto@ISA,seetheparentpragma.Thediscouragedbasepragmadoesthisaswell,butshouldnotbeusedexceptwhencompatibilitywiththediscouragedfieldspragmaisrequired.
#$^M
Bydefault,runningoutofmemoryisanuntrappable,fatalerror.However,ifsuitablybuilt,Perlcanusethecontentsof$^Masanemergencymemorypoolafterdie()ing.SupposethatyourPerlwerecompiledwith-DPERL_EMERGENCY_SBRKandusedPerl'smalloc.Then
$^M='a'x(1<<16);
wouldallocatea64Kbufferforuseinanemergency.SeetheINSTALLfileinthePerldistributionforinformationonhowtoaddcustomCcompilationflagswhencompilingperl.Todiscouragecasualuseofthisadvancedfeature,thereisnoEnglishlongnameforthisvariable.
ThisvariablewasaddedinPerl5.004.
#$OSNAME
#$^O
ThenameoftheoperatingsystemunderwhichthiscopyofPerlwasbuilt,asdeterminedduringtheconfigurationprocess.Forexamplessee"PLATFORMS"inperlport.
Thevalueisidenticalto$Config{'osname'}.SeealsoConfigandthe-Vcommand-lineswitchdocumentedinperlrun.
InWindowsplatforms,$^Oisnotveryhelpful:sinceitisalwaysMSWin32,itdoesn'ttellthedifferencebetween95/98/ME/NT/2000/XP/CE/.NET.UseWin32::GetOSName()orWin32::GetOSVersion()(seeWin32andperlport)todistinguishbetweenthevariants.
ThisvariablewasaddedinPerl5.003.
#%SIG
Thehash%SIGcontainssignalhandlersforsignals.Forexample:
subhandler{#1stargumentissignalname
my($sig)=@_;
print"CaughtaSIG$sig--shuttingdown\n";
close(LOG);
exit(0);
}
$SIG{'INT'}=\&handler;
$SIG{'QUIT'}=\&handler;
...
$SIG{'INT'}='DEFAULT';#restoredefaultaction
$SIG{'QUIT'}='IGNORE';#ignoreSIGQUIT
Usingavalueof'IGNORE'usuallyhastheeffectofignoringthesignal,exceptfortheCHLDsignal.Seeperlipcformoreaboutthisspecialcase.Usinganemptystringorundefasthevaluehasthesameeffectas'DEFAULT'.
Herearesomeotherexamples:
$SIG{"PIPE"}="Plumber";#assumesmain::Plumber(not
#recommended)
$SIG{"PIPE"}=\&Plumber;#justfine;assumecurrent
#Plumber
$SIG{"PIPE"}=*Plumber;#somewhatesoteric
$SIG{"PIPE"}=Plumber();#oops,whatdidPlumber()
#return??
Besurenottouseabarewordasthenameofasignalhandler,lestyouinadvertentlycallit.
Usingastringthatdoesn'tcorrespondtoanyexistingfunctionoraglobthatdoesn'tcontainacodeslotisequivalentto'IGNORE',butawarningisemittedwhenthehandlerisbeingcalled(thewarningisnotemittedfortheinternalhooksdescribedbelow).
Ifyoursystemhasthesigaction()functionthensignalhandlersareinstalledusingit.Thismeansyougetreliablesignalhandling.
ThedefaultdeliverypolicyofsignalschangedinPerlv5.8.0fromimmediate(alsoknownas"unsafe")todeferred,alsoknownas"safesignals".Seeperlipcformoreinformation.
Certaininternalhookscanbealsosetusingthe%SIGhash.Theroutineindicatedby$SIG{__WARN__}iscalledwhenawarningmessageisabouttobeprinted.Thewarningmessageispassedasthefirstargument.Thepresenceofa__WARN__hookcausestheordinaryprintingofwarningstoSTDERRtobesuppressed.Youcanusethistosavewarningsinavariable,orturnwarningsintofatalerrors,likethis:
local$SIG{__WARN__}=sub{die$_[0]};
eval$proggie;
Asthe'IGNORE'hookisnotsupportedby__WARN__,itseffectisthesameasusing'DEFAULT'.Youcandisablewarningsusingtheemptysubroutine:
local$SIG{__WARN__}=sub{};
Theroutineindicatedby$SIG{__DIE__}iscalledwhenafatalexceptionisabouttobethrown.Theerrormessageispassedasthefirstargument.Whena__DIE__hookroutinereturns,theexceptionprocessingcontinuesasitwouldhaveintheabsenceofthehook,unlessthehookroutineitselfexitsviaagoto&sub,aloopexit,oradie().The__DIE__handlerisexplicitlydisabledduringthecall,sothatyoucandiefroma__DIE__handler.Similarlyfor__WARN__.
The$SIG{__DIE__}hookiscalledeveninsideaneval().Itwasneverintendedtohappenthisway,butanimplementationglitchmadethispossible.Thisusedtobedeprecated,asitallowedstrangeactionatadistancelikerewritingapendingexceptionin$@.Planstorectifythishavebeenscrapped,asusersfoundthatrewritingapendingexceptionisactuallyausefulfeature,andnotabug.
The$SIG{__DIE__}doesn'tsupport'IGNORE';ithasthesameeffectas'DEFAULT'.
__DIE__/__WARN__handlersareveryspecialinonerespect:theymaybecalledtoreport(probable)errorsfoundbytheparser.Insuchacasetheparsermaybeininconsistentstate,soanyattempttoevaluatePerlcodefromsuchahandlerwillprobablyresultinasegfault.ThismeansthatwarningsorerrorsthatresultfromparsingPerlshouldbeusedwithextremecaution,likethis:
requireCarpifdefined$^S;
Carp::confess("Somethingwrong")ifdefined&Carp::confess;
die"Somethingwrong,butcouldnotloadCarptogive"
."backtrace...\n\t"
."ToseebacktracetrystartingPerlwith-MCarpswitch";
HerethefirstlinewillloadCarpunlessitistheparserwhocalledthehandler.ThesecondlinewillprintbacktraceanddieifCarpwasavailable.ThethirdlinewillbeexecutedonlyifCarpwasnotavailable.
Havingtoeventhinkaboutthe$^Svariableinyourexceptionhandlersissimplywrong.$SIG{__DIE__}ascurrentlyimplementedinvitesgrievousanddifficulttotrackdownerrors.AvoiditanduseanEND{}orCORE::GLOBAL::dieoverrideinstead.
See"die"inperlfunc,"warn"inperlfunc,"eval"inperlfunc,andwarningsforadditionalinformation.
#$BASETIME
#$^T
Thetimeatwhichtheprogrambeganrunning,insecondssincetheepoch(beginningof1970).Thevaluesreturnedbythe-M,-A,and-Cfiletestsarebasedonthisvalue.
#$PERL_VERSION
#$^V
Therevision,version,andsubversionofthePerlinterpreter,representedasaversionobject.
Thisvariablefirstappearedinperlv5.6.0;earlierversionsofperlwillseeanundefinedvalue.Beforeperlv5.10.0$^Vwasrepresentedasav-stringratherthanaversionobject.
$^VcanbeusedtodeterminewhetherthePerlinterpreterexecutingascriptisintherightrangeofversions.Forexample:
warn"Hashesnotrandomized!\n"if!$^Vor$^Vltv5.8.1
Whileversionobjectsoverloadstringification,toportablyconvert$^Vintoitsstringrepresentation,usesprintf()'s"%vd"conversion,whichworksforbothv-stringsorversionobjects:
printf"versionisv%vd\n",$^V;#Perl'sversion
SeethedocumentationofuseVERSIONandrequireVERSIONforaconvenientwaytofailiftherunningPerlinterpreteristooold.
Seealso"$]"foradecimalrepresentationofthePerlversion.
Themainadvantageof$^Vover$]isthat,forPerlv5.10.0orlater,itoverloadsoperators,allowingeasycomparisonagainstotherversionrepresentations(e.g.decimal,literalv-string,"v1.2.3",orobjects).Thedisadvantageisthatpriortov5.10.0,itwasonlyaliteralv-string,whichcan'tbeeasilyprintedorcompared,whereasthebehaviorof$]isunchangedonallversionsofPerl.
Mnemonic:use^Vforaversionobject.
#$EXECUTABLE_NAME
#$^X
ThenameusedtoexecutethecurrentcopyofPerl,fromC'sargv[0]or(wheresupported)/proc/self/exe.
Dependingonthehostoperatingsystem,thevalueof$^Xmaybearelativeorabsolutepathnameoftheperlprogramfile,ormaybethestringusedtoinvokeperlbutnotthepathnameoftheperlprogramfile.Also,mostoperatingsystemspermitinvokingprogramsthatarenotinthePATHenvironmentvariable,sothereisnoguaranteethatthevalueof$^XisinPATH.ForVMS,thevaluemayormaynotincludeaversionnumber.
Youusuallycanusethevalueof$^Xtore-invokeanindependentcopyofthesameperlthatiscurrentlyrunning,e.g.,
@first_run=`$^X-le"printintrand100for1..100"`;
Butrecallthatnotalloperatingsystemssupportforkingorcapturingoftheoutputofcommands,sothiscomplexstatementmaynotbeportable.
Itisnotsafetousethevalueof$^Xasapathnameofafile,assomeoperatingsystemsthathaveamandatorysuffixonexecutablefilesdonotrequireuseofthesuffixwheninvokingacommand.Toconvertthevalueof$^Xtoapathname,usethefollowingstatements:
#Buildupasetoffilenames(notcommandnames).
useConfig;
my$this_perl=$^X;
if($^One'VMS'){
$this_perl.=$Config{_exe}
unless$this_perl=~m/$Config{_exe}$/i;
}
BecausemanyoperatingsystemspermitanyonewithreadaccesstothePerlprogramfiletomakeacopyofit,patchthecopy,andthenexecutethecopy,thesecurity-consciousPerlprogrammershouldtakecaretoinvoketheinstalledcopyofperl,notthecopyreferencedby$^X.Thefollowingstatementsaccomplishthisgoal,andproduceapathnamethatcanbeinvokedasacommandorreferencedasafile.
useConfig;
my$secure_perl_path=$Config{perlpath};
if($^One'VMS'){
$secure_perl_path.=$Config{_exe}
unless$secure_perl_path=~m/$Config{_exe}$/i;
}
#Variablesrelatedtoregularexpressions
Mostofthespecialvariablesrelatedtoregularexpressionsaresideeffects.Perlsetsthesevariableswhenithasasuccessfulmatch,soyoushouldcheckthematchresultbeforeusingthem.Forinstance:
if(/P(A)TT(ER)N/){
print"Ifound$1and$2\n";
}
Thesevariablesareread-onlyanddynamically-scoped,unlesswenoteotherwise.
Thedynamicnatureoftheregularexpressionvariablesmeansthattheirvalueislimitedtotheblockthattheyarein,asdemonstratedbythisbitofcode:
my$outer='WallaceandGrommit';
my$inner='MuttandJeff';
my$pattern=qr/(\S+)and(\S+)/;
subshow_n{print"\$1is$1;\$2is$2\n"}
{
OUTER:
show_n()if$outer=~m/$pattern/;
INNER:{
show_n()if$inner=~m/$pattern/;
}
show_n();
}
TheoutputshowsthatwhileintheOUTERblock,thevaluesof$1and$2arefromthematchagainst$outer.InsidetheINNERblock,thevaluesof$1and$2arefromthematchagainst$inner,butonlyuntiltheendoftheblock(i.e.thedynamicscope).AftertheINNERblockcompletes,thevaluesof$1and$2returntothevaluesforthematchagainst$outereventhoughwehavenotmadeanothermatch:
$1isWallace;$2isGrommit
$1isMutt;$2isJeff
$1isWallace;$2isGrommit
#Performanceissues
TraditionallyinPerl,anyuseofanyofthethreevariables$`,$&or$'(ortheiruseEnglishequivalents)anywhereinthecode,causedallsubsequentsuccessfulpatternmatchestomakeacopyofthematchedstring,incasethecodemightsubsequentlyaccessoneofthosevariables.Thisimposedaconsiderableperformancepenaltyacrossthewholeprogram,sogenerallytheuseofthesevariableshasbeendiscouraged.
InPerl5.6.0the@-and@+dynamicarrayswereintroducedthatsupplytheindicesofsuccessfulmatches.Soyoucouldforexampledothis:
$str=~/pattern/;
print$`,$&,$';#bad:performancehit
print#good:noperformancehit
substr($str,0,$-[0]),
substr($str,$-[0],$+[0]-$-[0]),
substr($str,$+[0]);
InPerl5.10.0the/pmatchoperatorflagandthe${^PREMATCH},${^MATCH},and${^POSTMATCH}variableswereintroduced,thatallowedyoutosufferthepenaltiesonlyonpatternsmarkedwith/p.
InPerl5.18.0onwards,perlstartednotingthepresenceofeachofthethreevariablesseparately,andonlycopiedthatpartofthestringrequired;soin
$`;$&;"abcdefgh"=~/d/
perlwouldonlycopythe"abcd"partofthestring.Thatcouldmakeabigdifferenceinsomethinglike
$str='x'x1_000_000;
$&;#whoops
$str=~/x/g#onecharcopiedamilliontimes,notamillionchars
InPerl5.20.0anewcopy-on-writesystemwasenabledbydefault,whichfinallyfixesallperformanceissueswiththesethreevariables,andmakesthemsafetouseanywhere.
TheDevel::NYTProfandDevel::FindAmpersandmodulescanhelpyoufindusesoftheseproblematicmatchvariablesinyourcode.
#$($1,$2,...)
Containsthesubpatternfromthecorrespondingsetofcapturingparenthesesfromthelastsuccessfulpatternmatch,notcountingpatternsmatchedinnestedblocksthathavebeenexitedalready.
Notethereisadistinctionbetweenacapturebufferwhichmatchestheemptystringacapturebufferwhichisoptional.Eg,(x?)and(x)?Thelattermaybeundef,theformernot.
Thesevariablesareread-onlyanddynamically-scoped.
Mnemonic:like\digits.
#@{^CAPTURE}
Anarraywhichexposesthecontentsofthecapturebuffers,ifany,ofthelastsuccessfulpatternmatch,notcountingpatternsmatchedinnestedblocksthathavebeenexitedalready.
Notethatthe0indexof@{^CAPTURE}isequivalentto$1,the1indexisequivalentto$2,etc.
if("foal"=~/(.)(.)(.)(.)/){
printjoin"-",@{^CAPTURE};
}
shouldoutput"f-o-a-l".
Seealso"$($1,$2,...)","%{^CAPTURE}"and"%{^CAPTURE_ALL}".
Notethatunlikemostotherregexmagicvariablesthereisnosingleletterequivalentto@{^CAPTURE}.Alsobeawarethatwheninterpolatingsubscriptsofthisarrayyoumustusethedemarcatedvariableform,forinstance
print"${^CAPTURE[0]}"
see"Demarcatedvariablenamesusingbraces"inperldataformoreinformationonthisformanditsuses.
Thisvariablewasaddedin5.25.7
#$MATCH
#$&
Thestringmatchedbythelastsuccessfulpatternmatch(notcountinganymatcheshiddenwithinaBLOCKoreval()enclosedbythecurrentBLOCK).
See"Performanceissues"abovefortheseriousperformanceimplicationsofusingthisvariable(evenonce)inyourcode.
Thisvariableisread-onlyanddynamically-scoped.
Mnemonic:like&insomeeditors.
#${^MATCH}
Thisissimilarto$&($MATCH)exceptthatitdoesnotincurtheperformancepenaltyassociatedwiththatvariable.
See"Performanceissues"above.
InPerlv5.18andearlier,itisonlyguaranteedtoreturnadefinedvaluewhenthepatternwascompiledorexecutedwiththe/pmodifier.InPerlv5.20,the/pmodifierdoesnothing,so${^MATCH}doesthesamethingas$MATCH.
ThisvariablewasaddedinPerlv5.10.0.
Thisvariableisread-onlyanddynamically-scoped.
#$PREMATCH
#$`
Thestringprecedingwhateverwasmatchedbythelastsuccessfulpatternmatch,notcountinganymatcheshiddenwithinaBLOCKorevalenclosedbythecurrentBLOCK.
See"Performanceissues"abovefortheseriousperformanceimplicationsofusingthisvariable(evenonce)inyourcode.
Thisvariableisread-onlyanddynamically-scoped.
Mnemonic:`oftenprecedesaquotedstring.
#${^PREMATCH}
Thisissimilarto$`($PREMATCH)exceptthatitdoesnotincurtheperformancepenaltyassociatedwiththatvariable.
See"Performanceissues"above.
InPerlv5.18andearlier,itisonlyguaranteedtoreturnadefinedvaluewhenthepatternwascompiledorexecutedwiththe/pmodifier.InPerlv5.20,the/pmodifierdoesnothing,so${^PREMATCH}doesthesamethingas$PREMATCH.
ThisvariablewasaddedinPerlv5.10.0.
Thisvariableisread-onlyanddynamically-scoped.
#$POSTMATCH
#$'
Thestringfollowingwhateverwasmatchedbythelastsuccessfulpatternmatch(notcountinganymatcheshiddenwithinaBLOCKoreval()enclosedbythecurrentBLOCK).Example:
local$_='abcdefghi';
/def/;
print"$`:$&:$'\n";#printsabc:def:ghi
See"Performanceissues"abovefortheseriousperformanceimplicationsofusingthisvariable(evenonce)inyourcode.
Thisvariableisread-onlyanddynamically-scoped.
Mnemonic:'oftenfollowsaquotedstring.
#${^POSTMATCH}
Thisissimilarto$'($POSTMATCH)exceptthatitdoesnotincurtheperformancepenaltyassociatedwiththatvariable.
See"Performanceissues"above.
InPerlv5.18andearlier,itisonlyguaranteedtoreturnadefinedvaluewhenthepatternwascompiledorexecutedwiththe/pmodifier.InPerlv5.20,the/pmodifierdoesnothing,so${^POSTMATCH}doesthesamethingas$POSTMATCH.
ThisvariablewasaddedinPerlv5.10.0.
Thisvariableisread-onlyanddynamically-scoped.
#$LAST_PAREN_MATCH
#$+
Thetextmatchedbythehighestusedcapturegroupofthelastsuccessfulsearchpattern.Itislogicallyequivalenttothehighestnumberedcapturevariable($1,$2,...)whichhasadefinedvalue.
Thisisusefulifyoudon'tknowwhichoneofasetofalternativepatternsmatched.Forexample:
/Version:(.*)|Revision:(.*)/&&($rev=$+);
Thisvariableisread-onlyanddynamically-scoped.
Mnemonic:bepositiveandforwardlooking.
#$LAST_SUBMATCH_RESULT
#$^N
Thetextmatchedbytheusedgroupmost-recentlyclosed(i.e.thegroupwiththerightmostclosingparenthesis)ofthelastsuccessfulsearchpattern.Thisissubtlydifferentfrom$+.Forexamplein
"ab"=~/^((.)(.))$/
wehave
$1,$^Nhavethevalue"ab"
$2hasthevalue"a"
$3,$+havethevalue"b"
Thisisprimarilyusedinside(?{...})blocksforexaminingtextrecentlymatched.Forexample,toeffectivelycapturetexttoavariable(inadditionto$1,$2,etc.),replace(...)with
(?:(...)(?{$var=$^N}))
Bysettingandthenusing$varinthiswayrelievesyoufromhavingtoworryaboutexactlywhichnumberedsetofparenthesestheyare.
ThisvariablewasaddedinPerlv5.8.0.
Mnemonic:the(possibly)Nestedparenthesisthatmostrecentlyclosed.
#@LAST_MATCH_END
#@+
Thisarrayholdstheoffsetsoftheendsofthelastsuccessfulsubmatchesinthecurrentlyactivedynamicscope.$+[0]istheoffsetintothestringoftheendoftheentirematch.Thisisthesamevalueaswhattheposfunctionreturnswhencalledonthevariablethatwasmatchedagainst.Thenthelementofthisarrayholdstheoffsetofthenthsubmatch,so$+[1]istheoffsetpastwhere$1ends,$+[2]theoffsetpastwhere$2ends,andsoon.Youcanuse$#+todeterminehowmanysubgroupswereinthelastsuccessfulmatch.Seetheexamplesgivenforthe@-variable.
ThisvariablewasaddedinPerlv5.6.0.
#%{^CAPTURE}
#%LAST_PAREN_MATCH
#%+
Similarto@+,the%+hashallowsaccesstothenamedcapturebuffers,shouldtheyexist,inthelastsuccessfulmatchinthecurrentlyactivedynamicscope.
Forexample,$+{foo}isequivalentto$1afterthefollowingmatch:
'foo'=~/(?foo)/;
Thekeysofthe%+hashlistonlythenamesofbuffersthathavecaptured(andthatarethusassociatedtodefinedvalues).
Ifmultipledistinctcapturegroupshavethesamename,then$+{NAME}willrefertotheleftmostdefinedgroupinthematch.
Theunderlyingbehaviourof%+isprovidedbytheTie::Hash::NamedCapturemodule.
Note:%-and%+aretiedviewsintoacommoninternalhashassociatedwiththelastsuccessfulregularexpression.Thereforemixingiterativeaccesstothemviaeachmayhaveunpredictableresults.Likewise,ifthelastsuccessfulmatchchanges,thentheresultsmaybesurprising.
ThisvariablewasaddedinPerlv5.10.0.The%{^CAPTURE}aliaswasaddedin5.25.7.
Thisvariableisread-onlyanddynamically-scoped.
#@LAST_MATCH_START
#@-
$-[0]istheoffsetofthestartofthelastsuccessfulmatch.$-[n]istheoffsetofthestartofthesubstringmatchedbyn-thsubpattern,orundefifthesubpatterndidnotmatch.
Thus,afteramatchagainst$_,$&coincideswithsubstr$_,$-[0],$+[0]-$-[0].Similarly,$ncoincideswithsubstr$_,$-[n],$+[n]-$-[n]if$-[n]isdefined,and$+coincideswithsubstr$_,$-[$#-],$+[$#-]-$-[$#-].Onecanuse$#-tofindthelastmatchedsubgroupinthelastsuccessfulmatch.Contrastwith$#+,thenumberofsubgroupsintheregularexpression.Comparewith@+.
Thisarrayholdstheoffsetsofthebeginningsofthelastsuccessfulsubmatchesinthecurrentlyactivedynamicscope.$-[0]istheoffsetintothestringofthebeginningoftheentirematch.Thenthelementofthisarrayholdstheoffsetofthenthsubmatch,so$-[1]istheoffsetwhere$1begins,$-[2]theoffsetwhere$2begins,andsoon.
Afteramatchagainstsomevariable$var:
#$`isthesameassubstr($var,0,$-[0])
#$&isthesameassubstr($var,$-[0],$+[0]-$-[0])
#$'isthesameassubstr($var,$+[0])
#$1isthesameassubstr($var,$-[1],$+[1]-$-[1])
#$2isthesameassubstr($var,$-[2],$+[2]-$-[2])
#$3isthesameassubstr($var,$-[3],$+[3]-$-[3])
ThisvariablewasaddedinPerlv5.6.0.
#%{^CAPTURE_ALL}
#%-
Similarto%+,thisvariableallowsaccesstothenamedcapturegroupsinthelastsuccessfulmatchinthecurrentlyactivedynamicscope.Toeachcapturegroupnamefoundintheregularexpression,itassociatesareferencetoanarraycontainingthelistofvaluescapturedbyallbufferswiththatname(shouldtherebeseveralofthem),intheorderwheretheyappear.
Here'sanexample:
if('1234'=~/(?1)(?2)(?3)(?4)/){
foreachmy$bufname(sortkeys%-){
my$ary=$-{$bufname};
foreachmy$idx(0..$#$ary){
print"\$-{$bufname}[$idx]:",
(defined($ary->[$idx])
?"'$ary->[$idx]'"
:"undef"),
"\n";
}
}
}
wouldprintout:
$-{A}[0]:'1'
$-{A}[1]:'3'
$-{B}[0]:'2'
$-{B}[1]:'4'
Thekeysofthe%-hashcorrespondtoallbuffernamesfoundintheregularexpression.
Thebehaviourof%-isimplementedviatheTie::Hash::NamedCapturemodule.
Note:%-and%+aretiedviewsintoacommoninternalhashassociatedwiththelastsuccessfulregularexpression.Thereforemixingiterativeaccesstothemviaeachmayhaveunpredictableresults.Likewise,ifthelastsuccessfulmatchchanges,thentheresultsmaybesurprising.
ThisvariablewasaddedinPerlv5.10.0.The%{^CAPTURE_ALL}aliaswasaddedin5.25.7.
Thisvariableisread-onlyanddynamically-scoped.
#$LAST_REGEXP_CODE_RESULT
#$^R
Theresultofevaluationofthelastsuccessful(?{code})regularexpressionassertion(seeperlre).Maybewrittento.
ThisvariablewasaddedinPerl5.005.
#${^RE_COMPILE_RECURSION_LIMIT}
Thecurrentvaluegivingthemaximumnumberofopenbutunclosedparentheticalgroupstheremaybeatanypointduringaregularexpressioncompilation.Thedefaultiscurrently1000nestedgroups.Youmayadjustitdependingonyourneedsandtheamountofmemoryavailable.
ThisvariablewasaddedinPerlv5.30.0.
#${^RE_DEBUG_FLAGS}
Thecurrentvalueoftheregexdebuggingflags.Setto0fornodebugoutputevenwhenthere'debug'moduleisloaded.Seerefordetails.
ThisvariablewasaddedinPerlv5.10.0.
#${^RE_TRIE_MAXBUF}
Controlshowcertainregexoptimisationsareappliedandhowmuchmemorytheyutilize.Thisvaluebydefaultis65536whichcorrespondstoa512kBtemporarycache.Setthistoahighervaluetotradememoryforspeedwhenmatchinglargealternations.Setittoalowervalueifyouwanttheoptimisationstobeasconservativeofmemoryaspossiblebutstilloccur,andsetittoanegativevaluetopreventtheoptimisationandconservethemostmemory.Undernormalsituationsthisvariableshouldbeofnointeresttoyou.
ThisvariablewasaddedinPerlv5.10.0.
#Variablesrelatedtofilehandles
VariablesthatdependonthecurrentlyselectedfilehandlemaybesetbycallinganappropriateobjectmethodontheIO::Handleobject,althoughthisislessefficientthanusingtheregularbuilt-invariables.(SummarylinesbelowforthiscontainthewordHANDLE.)Firstyoumustsay
useIO::Handle;
afterwhichyoumayuseeither
methodHANDLEEXPR
ormoresafely,
HANDLE->method(EXPR)
EachmethodreturnstheoldvalueoftheIO::Handleattribute.ThemethodseachtakeanoptionalEXPR,which,ifsupplied,specifiesthenewvaluefortheIO::Handleattributeinquestion.Ifnotsupplied,mostmethodsdonothingtothecurrentvalue--exceptforautoflush(),whichwillassumea1foryou,justtobedifferent.
BecauseloadingintheIO::Handleclassisanexpensiveoperation,youshouldlearnhowtousetheregularbuilt-invariables.
Afewofthesevariablesareconsidered"read-only".Thismeansthatifyoutrytoassigntothisvariable,eitherdirectlyorindirectlythroughareference,you'llraisearun-timeexception.
Youshouldbeverycarefulwhenmodifyingthedefaultvaluesofmostspecialvariablesdescribedinthisdocument.Inmostcasesyouwanttolocalizethesevariablesbeforechangingthem,sinceifyoudon't,thechangemayaffectothermoduleswhichrelyonthedefaultvaluesofthespecialvariablesthatyouhavechanged.Thisisoneofthecorrectwaystoreadthewholefileatonce:
openmy$fh,";
close$fh;
Butthefollowingcodeisquitebad:
openmy$fh,";
close$fh;
sincesomeothermodule,maywanttoreaddatafromsomefileinthedefault"linemode",soifthecodewehavejustpresentedhasbeenexecuted,theglobalvalueof$/isnowchangedforanyothercoderunninginsidethesamePerlinterpreter.
Usuallywhenavariableislocalizedyouwanttomakesurethatthischangeaffectstheshortestscopepossible.Sounlessyouarealreadyinsidesomeshort{}block,youshouldcreateoneyourself.Forexample:
my$content='';
openmy$fh,";
}
close$fh;
Hereisanexampleofhowyourowncodecangobroken:
for(1..3){
$\="\r\n";
nasty_break();
print"$_";
}
subnasty_break{
$\="\f";
#dosomethingwith$_
}
Youprobablyexpectthiscodetoprinttheequivalentof
"1\r\n2\r\n3\r\n"
butinsteadyouget:
"1\f2\f3\f"
Why?Becausenasty_break()modifies$\withoutlocalizingitfirst.Thevalueyousetinnasty_break()isstilltherewhenyoureturn.Thefixistoaddlocal()sothevaluedoesn'tleakoutofnasty_break():
local$\="\f";
It'seasytonoticetheprobleminsuchashortexample,butinmorecomplicatedcodeyouarelookingfortroubleifyoudon'tlocalizechangestothespecialvariables.
#$ARGV
Containsthenameofthecurrentfilewhenreadingfrom<>.
#@ARGV
Thearray@ARGVcontainsthecommand-lineargumentsintendedforthescript.$#ARGVisgenerallythenumberofargumentsminusone,because$ARGV[0]isthefirstargument,nottheprogram'scommandnameitself.See"$0"forthecommandname.
#ARGV
Thespecialfilehandlethatiteratesovercommand-linefilenamesin@ARGV.Usuallywrittenasthenullfilehandleintheangleoperator<>.NotethatcurrentlyARGVonlyhasitsmagicaleffectwithinthe<>operator;elsewhereitisjustaplainfilehandlecorrespondingtothelastfileopenedby<>.Inparticular,passing\*ARGVasaparametertoafunctionthatexpectsafilehandlemaynotcauseyourfunctiontoautomaticallyreadthecontentsofallthefilesin@ARGV.
#ARGVOUT
Thespecialfilehandlethatpointstothecurrentlyopenoutputfilewhendoingedit-in-placeprocessingwith-i.Usefulwhenyouhavetodoalotofinsertinganddon'twanttokeepmodifying$_.Seeperlrunforthe-iswitch.
#IO::Handle->output_field_separator(EXPR)
#$OUTPUT_FIELD_SEPARATOR
#$OFS
#$,
Theoutputfieldseparatorfortheprintoperator.Ifdefined,thisvalueisprintedbetweeneachofprint'sarguments.Defaultisundef.
Youcannotcalloutput_field_separator()onahandle,onlyasastaticmethod.SeeIO::Handle.
Mnemonic:whatisprintedwhenthereisa","inyourprintstatement.
#HANDLE->input_line_number(EXPR)
#$INPUT_LINE_NUMBER
#$NR
#$.
Currentlinenumberforthelastfilehandleaccessed.
EachfilehandleinPerlcountsthenumberoflinesthathavebeenreadfromit.(Dependingonthevalueof$/,Perl'sideaofwhatconstitutesalinemaynotmatchyours.)Whenalineisreadfromafilehandle(viareadline()or<>),orwhentell()orseek()iscalledonit,$.becomesanaliastothelinecounterforthatfilehandle.
Youcanadjustthecounterbyassigningto$.,butthiswillnotactuallymovetheseekpointer.Localizing$.willnotlocalizethefilehandle'slinecount.Instead,itwilllocalizeperl'snotionofwhichfilehandle$.iscurrentlyaliasedto.
$.isresetwhenthefilehandleisclosed,butnotwhenanopenfilehandleisreopenedwithoutaninterveningclose().Formoredetails,see"I/OOperators"inperlop.Because<>neverdoesanexplicitclose,linenumbersincreaseacrossARGVfiles(butseeexamplesin"eof"inperlfunc).
YoucanalsouseHANDLE->input_line_number(EXPR)toaccessthelinecounterforagivenfilehandlewithouthavingtoworryaboutwhichhandleyoulastaccessed.
Mnemonic:manyprogramsuse"."tomeanthecurrentlinenumber.
#IO::Handle->input_record_separator(EXPR)
#$INPUT_RECORD_SEPARATOR
#$RS
#$/
Theinputrecordseparator,newlinebydefault.ThisinfluencesPerl'sideaofwhata"line"is.Workslikeawk'sRSvariable,includingtreatingemptylinesasaterminatorifsettothenullstring(anemptylinecannotcontainanyspacesortabs).Youmaysetittoamulti-characterstringtomatchamulti-characterterminator,ortoundeftoreadthroughtheendoffile.Settingitto"\n\n"meanssomethingslightlydifferentthansettingto"",ifthefilecontainsconsecutiveemptylines.Settingto""willtreattwoormoreconsecutiveemptylinesasasingleemptyline.Settingto"\n\n"willblindlyassumethatthenextinputcharacterbelongstothenextparagraph,evenifit'sanewline.
local$/;#enable"slurp"mode
local$_=;#wholefilenowhere
s/\n[\t]+//g;
Remember:thevalueof$/isastring,notaregex.awkhastobebetterforsomething.:-)
Setting$/toanemptystring--theso-calledparagraphmode--meritsspecialattention.When$/issetto""andtheentirefileisreadinwiththatsetting,anysequenceofoneormoreconsecutivenewlinesatthebeginningofthefileisdiscarded.Withtheexceptionofthefinalrecordinthefile,eachsequenceofcharactersendingintwoormorenewlinesistreatedasonerecordandisreadintoendinexactlytwonewlines.Ifthelastrecordinthefileendsinzerooroneconsecutivenewlines,thatrecordisreadinwiththatnumberofnewlines.Ifthelastrecordendsintwoormoreconsecutivenewlines,itisreadinwithtwonewlineslikeallprecedingrecords.
Supposewewrotethefollowingstringtoafile:
my$string="\n\n\n";
$string.="alphabeta\ngammadelta\n\n\n";
$string.="epsilonzetaeta\n\n";
$string.="theta\n";
my$file='simple_file.txt';
openmy$OUT,'>',$fileordie;
print$OUT$string;
close$OUTordie;
Nowwereadthatfileinparagraphmode:
local$/="";#paragraphmode
openmy$IN,';
close$INordie;
@recordswillconsistofthese3strings:
(
"alphabeta\ngammadelta\n\n",
"epsilonzetaeta\n\n",
"theta\n",
)
Setting$/toareferencetoaninteger,scalarcontaininganinteger,orscalarthat'sconvertibletoanintegerwillattempttoreadrecordsinsteadoflines,withthemaximumrecordsizebeingthereferencedintegernumberofcharacters.Sothis:
local$/=\32768;#or\"32768",or\$var_containing_32768
openmy$fh,";
willreadarecordofnomorethan32768charactersfrom$fh.Ifyou'renotreadingfromarecord-orientedfile(oryourOSdoesn'thaverecord-orientedfiles),thenyou'lllikelygetafullchunkofdatawitheveryread.Ifarecordislargerthantherecordsizeyou'veset,you'llgettherecordbackinpieces.Tryingtosettherecordsizetozeroorlessisdeprecatedandwillcause$/tohavethevalueof"undef",whichwillcausereadinginthe(restofthe)wholefile.
Asof5.19.9setting$/toanyotherformofreferencewillthrowafatalexception.Thisisinpreparationforsupportingnewwaystoset$/inthefuture.
OnVMSonly,recordreadsbypassPerlIOlayersandanyassociatedbuffering,soyoumustnotmixrecordandnon-recordreadsonthesamefilehandle.Recordmodemixeswithlinemodeonlywhenthesamebufferinglayerisinuseforbothmodes.
Youcannotcallinput_record_separator()onahandle,onlyasastaticmethod.SeeIO::Handle.
Seealso"Newlines"inperlport.Alsosee"$.".
Mnemonic:/delimitslineboundarieswhenquotingpoetry.
#IO::Handle->output_record_separator(EXPR)
#$OUTPUT_RECORD_SEPARATOR
#$ORS
#$\
Theoutputrecordseparatorfortheprintoperator.Ifdefined,thisvalueisprintedafterthelastofprint'sarguments.Defaultisundef.
Youcannotcalloutput_record_separator()onahandle,onlyasastaticmethod.SeeIO::Handle.
Mnemonic:youset$\insteadofadding"\n"attheendoftheprint.Also,it'sjustlike$/,butit'swhatyouget"back"fromPerl.
#HANDLE->autoflush(EXPR)
#$OUTPUT_AUTOFLUSH
#$|
Ifsettononzero,forcesaflushrightawayandaftereverywriteorprintonthecurrentlyselectedoutputchannel.Defaultis0(regardlessofwhetherthechannelisreallybufferedbythesystemornot;$|tellsyouonlywhetheryou'veaskedPerlexplicitlytoflushaftereachwrite).STDOUTwilltypicallybelinebufferedifoutputistotheterminalandblockbufferedotherwise.Settingthisvariableisusefulprimarilywhenyouareoutputtingtoapipeorsocket,suchaswhenyouarerunningaPerlprogramunderrshandwanttoseetheoutputasit'shappening.Thishasnoeffectoninputbuffering.See"getc"inperlfuncforthat.See"select"inperlfunconhowtoselecttheoutputchannel.SeealsoIO::Handle.
Mnemonic:whenyouwantyourpipestobepipinghot.
#${^LAST_FH}
Thisread-onlyvariablecontainsareferencetothelast-readfilehandle.Thisissetby,readline,tell,eofandseek.Thisisthesamehandlethat$.andtellandeofwithoutargumentsuse.ItisalsothehandleusedwhenPerlappends",line1"toanerrororwarningmessage.
ThisvariablewasaddedinPerlv5.18.0.
#Variablesrelatedtoformats
Thespecialvariablesforformatsareasubsetofthoseforfilehandles.SeeperlformformoreinformationaboutPerl'sformats.
#$ACCUMULATOR
#$^A
Thecurrentvalueofthewrite()accumulatorforformat()lines.Aformatcontainsformline()callsthatputtheirresultinto$^A.Aftercallingitsformat,write()printsoutthecontentsof$^Aandempties.Soyouneverreallyseethecontentsof$^Aunlessyoucallformline()yourselfandthenlookatit.Seeperlformand"formlinePICTURE,LIST"inperlfunc.
#IO::Handle->format_formfeed(EXPR)
#$FORMAT_FORMFEED
#$^L
Whatformatsoutputasaformfeed.Thedefaultis\f.
Youcannotcallformat_formfeed()onahandle,onlyasastaticmethod.SeeIO::Handle.
#HANDLE->format_page_number(EXPR)
#$FORMAT_PAGE_NUMBER
#$%
Thecurrentpagenumberofthecurrentlyselectedoutputchannel.
Mnemonic:%ispagenumberinnroff.
#HANDLE->format_lines_left(EXPR)
#$FORMAT_LINES_LEFT
#$-
Thenumberoflinesleftonthepageofthecurrentlyselectedoutputchannel.
Mnemonic:lines_on_page-lines_printed.
#IO::Handle->format_line_break_charactersEXPR
#$FORMAT_LINE_BREAK_CHARACTERS
#$:
Thecurrentsetofcharactersafterwhichastringmaybebrokentofillcontinuationfields(startingwith^)inaformat.Thedefaultis"\n-",tobreakonaspace,newline,orahyphen.
Youcannotcallformat_line_break_characters()onahandle,onlyasastaticmethod.SeeIO::Handle.
Mnemonic:a"colon"inpoetryisapartofaline.
#HANDLE->format_lines_per_page(EXPR)
#$FORMAT_LINES_PER_PAGE
#$=
Thecurrentpagelength(printablelines)ofthecurrentlyselectedoutputchannel.Thedefaultis60.
Mnemonic:=hashorizontallines.
#HANDLE->format_top_name(EXPR)
#$FORMAT_TOP_NAME
#$^
Thenameofthecurrenttop-of-pageformatforthecurrentlyselectedoutputchannel.Thedefaultisthenameofthefilehandlewith_TOPappended.Forexample,thedefaultformattopnamefortheSTDOUTfilehandleisSTDOUT_TOP.
Mnemonic:pointstotopofpage.
#HANDLE->format_name(EXPR)
#$FORMAT_NAME
#$~
Thenameofthecurrentreportformatforthecurrentlyselectedoutputchannel.Thedefaultformatnameisthesameasthefilehandlename.Forexample,thedefaultformatnamefortheSTDOUTfilehandleisjustSTDOUT.
Mnemonic:brotherto$^.
#ErrorVariables
Thevariables$@,$!,$^E,and$?containinformationaboutdifferenttypesoferrorconditionsthatmayappearduringexecutionofaPerlprogram.Thevariablesareshownorderedbythe"distance"betweenthesubsystemwhichreportedtheerrorandthePerlprocess.TheycorrespondtoerrorsdetectedbythePerlinterpreter,Clibrary,operatingsystem,oranexternalprogram,respectively.
Toillustratethedifferencesbetweenthesevariables,considerthefollowingPerlexpression,whichusesasingle-quotedstring.Afterexecutionofthisstatement,perlmayhavesetallfourspecialerrorvariables:
evalq{
openmy$pipe,"/cdrom/install|"ordie$!;
my@res=;
close$pipeordie"badpipe:$?,$!";
};
Whenperlexecutestheeval()expression,ittranslatestheopen(),,andclosecallsintheCrun-timelibraryandthencetotheoperatingsystemkernel.perlsets$!totheClibrary'serrnoifoneofthesecallsfails.
$@issetifthestringtobeeval-eddidnotcompile(thismayhappenifopenorclosewereimportedwithbadprototypes),orifPerlcodeexecutedduringevaluationdie()d.Inthesecasesthevalueof$@isthecompileerror,ortheargumenttodie(whichwillinterpolate$!and$?).(SeealsoFatal,though.)
Underafewoperatingsystems,$^Emaycontainamoreverboseerrorindicator,suchasinthiscase,"CDROMtraynotclosed."Systemsthatdonotsupportextendederrormessagesleave$^Ethesameas$!.
Finally,$?maybesettoanon-0valueiftheexternalprogram/cdrom/installfails.Theuppereightbitsreflectspecificerrorconditionsencounteredbytheprogram(theprogram'sexit()value).Thelowereightbitsreflectmodeoffailure,likesignaldeathandcoredumpinformation.Seewait(2)fordetails.Incontrastto$!and$^E,whicharesetonlyifanerrorconditionisdetected,thevariable$?issetoneachwaitorpipeclose,overwritingtheoldvalue.Thisismorelike$@,whichoneveryeval()isalwayssetonfailureandclearedonsuccess.
Formoredetails,seetheindividualdescriptionsat$@,$!,$^E,and$?.
#${^CHILD_ERROR_NATIVE}
Thenativestatusreturnedbythelastpipeclose,backtick(``)command,successfulcalltowait()orwaitpid(),orfromthesystem()operator.OnPOSIX-likesystemsthisvaluecanbedecodedwiththeWIFEXITED,WEXITSTATUS,WIFSIGNALED,WTERMSIG,WIFSTOPPED,andWSTOPSIGfunctionsprovidedbythePOSIXmodule.
UnderVMSthisreflectstheactualVMSexitstatus;i.e.itisthesameas$?whenthepragmausevmsish'status'isineffect.
ThisvariablewasaddedinPerlv5.10.0.
#$EXTENDED_OS_ERROR
#$^E
Errorinformationspecifictothecurrentoperatingsystem.Atthemoment,thisdiffersfrom"$!"underonlyVMS,OS/2,andWin32(andforMacPerl).Onallotherplatforms,$^Eisalwaysjustthesameas$!.
UnderVMS,$^EprovidestheVMSstatusvaluefromthelastsystemerror.Thisismorespecificinformationaboutthelastsystemerrorthanthatprovidedby$!.Thisisparticularlyimportantwhen$!issettoEVMSERR.
UnderOS/2,$^EissettotheerrorcodeofthelastcalltoOS/2APIeitherviaCRT,ordirectlyfromperl.
UnderWin32,$^EalwaysreturnsthelasterrorinformationreportedbytheWin32callGetLastError()whichdescribesthelasterrorfromwithintheWin32API.MostWin32-specificcodewillreporterrorsvia$^E.ANSICandUnix-likecallsseterrnoandsomostportablePerlcodewillreporterrorsvia$!.
Caveatsmentionedinthedescriptionof"$!"generallyapplyto$^E,also.
ThisvariablewasaddedinPerl5.003.
Mnemonic:Extraerrorexplanation.
#$EXCEPTIONS_BEING_CAUGHT
#$^S
Currentstateoftheinterpreter.
$^SState
----------------------------------------------
undefParsingmodule,eval,ormainprogram
true(1)Executinganevalortryblock
false(0)Otherwise
Thefirststatemayhappenin$SIG{__DIE__}and$SIG{__WARN__}handlers.
TheEnglishname$EXCEPTIONS_BEING_CAUGHTisslightlymisleading,becausetheundefvaluedoesnotindicatewhetherexceptionsarebeingcaught,sincecompilationofthemainprogramdoesnotcatchexceptions.
ThisvariablewasaddedinPerl5.004.
#$WARNING
#$^W
Thecurrentvalueofthewarningswitch,initiallytrueif-wwasused,falseotherwise,butdirectlymodifiable.
Seealsowarnings.
Mnemonic:relatedtothe-wswitch.
#${^WARNING_BITS}
Thecurrentsetofwarningchecksenabledbytheusewarningspragma.Ithasthesamescopingasthe$^Hand%^Hvariables.TheexactvaluesareconsideredinternaltothewarningspragmaandmaychangebetweenversionsofPerl.
Eachtimeastatementcompletesbeingcompiled,thecurrentvalueof${^WARNING_BITS}isstoredwiththatstatement,andcanlaterberetrievedvia(caller($level))[9].
ThisvariablewasaddedinPerlv5.6.0.
#$OS_ERROR
#$ERRNO
#$!
Whenreferenced,$!retrievesthecurrentvalueoftheCerrnointegervariable.If$!isassignedanumericalvalue,thatvalueisstoredinerrno.Whenreferencedasastring,$!yieldsthesystemerrorstringcorrespondingtoerrno.
Manysystemorlibrarycallsseterrnoiftheyfail,toindicatethecauseoffailure.Theyusuallydonotseterrnotozeroiftheysucceedandmayseterrnotoanon-zerovalueonsuccess.Thismeanserrno,hence$!,ismeaningfulonlyimmediatelyafterafailure:
if(openmy$fh,">8),and$?&127giveswhichsignal,ifany,theprocessdiedfrom,and$?&128reportswhethertherewasacoredump.
Additionally,iftheh_errnovariableissupportedinC,itsvalueisreturnedvia$?ifanygethost*()functionfails.
IfyouhaveinstalledasignalhandlerforSIGCHLD,thevalueof$?willusuallybewrongoutsidethathandler.
InsideanENDsubroutine$?containsthevaluethatisgoingtobegiventoexit().Youcanmodify$?inanENDsubroutinetochangetheexitstatusofyourprogram.Forexample:
END{
$?=1if$?==255;#diewouldmakeit255
}
UnderVMS,thepragmausevmsish'status'makes$?reflecttheactualVMSexitstatus,insteadofthedefaultemulationofPOSIXstatus;see"$?"inperlvmsfordetails.
Mnemonic:similartoshandksh.
#$EVAL_ERROR
#$@
ThePerlerrorfromthelastevaloperator,i.e.thelastexceptionthatwascaught.ForevalBLOCK,thisiseitheraruntimeerrormessageorthestringorreferencediewascalledwith.TheevalSTRINGformalsocatchessyntaxerrorsandothercompiletimeexceptions.
Ifnoerroroccurs,evalsets$@totheemptystring.
Warningmessagesarenotcollectedinthisvariable.Youcan,however,setuparoutinetoprocesswarningsbysetting$SIG{__WARN__}asdescribedin"%SIG".
Mnemonic:Wherewastheerror"at"?
#Variablesrelatedtotheinterpreterstate
Thesevariablesprovideinformationaboutthecurrentinterpreterstate.
#$COMPILING
#$^C
Thecurrentvalueoftheflagassociatedwiththe-cswitch.Mainlyofusewith-MO=...toallowcodetoalteritsbehaviorwhenbeingcompiled,suchasforexampletoAUTOLOADatcompiletimeratherthannormal,deferredloading.Setting$^C=1issimilartocallingB::minus_c.
ThisvariablewasaddedinPerlv5.6.0.
#$DEBUGGING
#$^D
Thecurrentvalueofthedebuggingflags.Maybereadorset.Likeitscommand-lineequivalent,youcanusenumericorsymbolicvalues,e.g.$^D=10or$^D="st".See"-Dnumber"inperlrun.Thecontentsofthisvariablealsoaffectsthedebuggeroperation.See"DebuggerInternals"inperldebguts.
Mnemonic:valueof-Dswitch.
#${^GLOBAL_PHASE}
Thecurrentphaseoftheperlinterpreter.
Possiblevaluesare:
#CONSTRUCT
ThePerlInterpreter*isbeingconstructedviaperl_construct.ThisvalueismostlythereforcompletenessandforuseviatheunderlyingCvariablePL_phase.It'snotreallypossibleforPerlcodetobeexecutedunlessconstructionoftheinterpreterisfinished.
#START
Thisistheglobalcompile-time.Thatincludes,basically,everyBEGINblockexecuteddirectlyorindirectlyfromduringthecompile-timeofthetop-levelprogram.
Thisphaseisnotcalled"BEGIN"toavoidconfusionwithBEGIN-blocks,asthoseareexecutedduringcompile-timeofanycompilationunit,notjustthetop-levelprogram.Anew,localisedcompile-timeenteredatrun-time,forexamplebyconstructsaseval"useSomeModule"arenotglobalinterpreterphases,andthereforearen'treflectedby${^GLOBAL_PHASE}.
#CHECK
ExecutionofanyCHECKblocks.
#INIT
Similarto"CHECK",butforINIT-blocks,notCHECKblocks.
#RUN
Themainrun-time,i.e.theexecutionofPL_main_root.
#END
ExecutionofanyENDblocks.
#DESTRUCT
Globaldestruction.
Alsonotethatthere'snovalueforUNITCHECK-blocks.That'sbecausethosearerunforeachcompilationunitindividually,andthereforeisnotaglobalinterpreterphase.
Noteveryprogramhastogothrougheachofthepossiblephases,buttransitionfromonephasetoanothercanonlyhappenintheorderdescribedintheabovelist.
AnexampleofallofthephasesPerlcodecansee:
BEGIN{print"compile-time:${^GLOBAL_PHASE}\n"}
INIT{print"init-time:${^GLOBAL_PHASE}\n"}
CHECK{print"check-time:${^GLOBAL_PHASE}\n"}
{
packagePrint::Phase;
subnew{
my($class,$time)=@_;
returnbless\$time,$class;
}
subDESTROY{
my$self=shift;
print"$$self:${^GLOBAL_PHASE}\n";
}
}
print"run-time:${^GLOBAL_PHASE}\n";
my$runtime=Print::Phase->new(
"lexicalvariablesaregarbagecollectedbeforeEND"
);
END{print"end-time:${^GLOBAL_PHASE}\n"}
our$destruct=Print::Phase->new(
"packagevariablesaregarbagecollectedafterEND"
);
Thiswillprintout
compile-time:START
check-time:CHECK
init-time:INIT
run-time:RUN
lexicalvariablesaregarbagecollectedbeforeEND:RUN
end-time:END
packagevariablesaregarbagecollectedafterEND:DESTRUCT
ThisvariablewasaddedinPerl5.14.0.
#$^H
WARNING:Thisvariableisstrictlyforinternaluseonly.Itsavailability,behavior,andcontentsaresubjecttochangewithoutnotice.
Thisvariablecontainscompile-timehintsforthePerlinterpreter.AttheendofcompilationofaBLOCKthevalueofthisvariableisrestoredtothevaluewhentheinterpreterstartedtocompiletheBLOCK.
Eachtimeastatementcompletesbeingcompiled,thecurrentvalueof$^Hisstoredwiththatstatement,andcanlaterberetrievedvia(caller($level))[8].
Whenperlbeginstoparseanyblockconstructthatprovidesalexicalscope(e.g.,evalbody,requiredfile,subroutinebody,loopbody,orconditionalblock),theexistingvalueof$^Hissaved,butitsvalueisleftunchanged.Whenthecompilationoftheblockiscompleted,itregainsthesavedvalue.Betweenthepointswhereitsvalueissavedandrestored,codethatexecuteswithinBEGINblocksisfreetochangethevalueof$^H.
Thisbehaviorprovidesthesemanticoflexicalscoping,andisusedin,forinstance,theusestrictpragma.
Thecontentsshouldbeaninteger;differentbitsofitareusedfordifferentpragmaticflags.Here'sanexample:
subadd_100{$^H|=0x100}
subfoo{
BEGIN{add_100()}
bar->baz($boon);
}
ConsiderwhathappensduringexecutionoftheBEGINblock.AtthispointtheBEGINblockhasalreadybeencompiled,butthebodyoffoo()isstillbeingcompiled.Thenewvalueof$^Hwillthereforebevisibleonlywhilethebodyoffoo()isbeingcompiled.
SubstitutionofBEGIN{add_100()}blockwith:
BEGIN{requirestrict;strict->import('vars')}
demonstrateshowusestrict'vars'isimplemented.Here'saconditionalversionofthesamelexicalpragma:
BEGIN{
requirestrict;strict->import('vars')if$condition
}
ThisvariablewasaddedinPerl5.003.
#%^H
The%^Hhashprovidesthesamescopingsemanticas$^H.Thismakesitusefulforimplementationoflexicallyscopedpragmas.Seeperlpragma.Alltheentriesarestringifiedwhenaccessedatruntime,soonlysimplevaluescanbeaccommodated.Thismeansnopointerstoobjects,forexample.
Eachtimeastatementcompletesbeingcompiled,thecurrentvalueof%^Hisstoredwiththatstatement,andcanlaterberetrievedvia(caller($level))[10].
Whenputtingitemsinto%^H,inordertoavoidconflictingwithotherusersofthehashthereisaconventionregardingwhichkeystouse.Amoduleshoulduseonlykeysthatbeginwiththemodule'sname(thenameofitsmainpackage)anda"/"character.Forexample,amoduleFoo::BarshouldusekeyssuchasFoo::Bar/baz.
ThisvariablewasaddedinPerlv5.6.0.
#${^OPEN}
AninternalvariableusedbyPerlIO.Astringintwoparts,separatedbya\0byte,thefirstpartdescribestheinputlayers,thesecondpartdescribestheoutputlayers.
Thisisthemechanismthatappliesthelexicaleffectsoftheopenpragma,andthemainprogramscopeeffectsoftheioorDoptionsforthe-Ccommand-lineswitchandPERL_UNICODEenvironmentvariable.
Thefunctionsaccept(),open(),pipe(),readpipe()(aswellastherelatedqxand`STRING`operators),socket(),socketpair(),andsysopen()areaffectedbythelexicalvalueofthisvariable.Theimplicit"ARGV"handleopenedbyreadline()(ortherelated<>and<<>>operators)onpassedfilenamesisalsoaffected(butnotifitopensSTDIN).Ifthisvariableisnotset,thesefunctionswillsetthedefaultlayersasdescribedin"Defaultsandhowtooverridethem"inPerlIO.
open()ignoresthisvariable(andthedefaultlayers)whencalledwith3argumentsandexplicitlayersarespecified.IndirectcallstothesefunctionsviamoduleslikeIO::Handlearenotaffectedastheyoccurinadifferentlexicalscope.Directoryhandlessuchasopenedbyopendir()arenotcurrentlyaffected.
ThisvariablewasaddedinPerlv5.8.0.
#$PERLDB
#$^P
Theinternalvariablefordebuggingsupport.Themeaningsofthevariousbitsaresubjecttochange,butcurrentlyindicate:
#0x01
Debugsubroutineenter/exit.
#0x02
Line-by-linedebugging.CausesDB::DB()subroutinetobecalledforeachstatementexecuted.Alsocausessavingsourcecodelines(like0x400).
#0x04
Switchoffoptimizations.
#0x08
Preservemoredataforfutureinteractiveinspections.
#0x10
Keepinfoaboutsourcelinesonwhichasubroutineisdefined.
#0x20
Startwithsingle-stepon.
#0x40
Usesubroutineaddressinsteadofnamewhenreporting.
#0x80
Reportgoto&subroutineaswell.
#0x100
Provideinformative"file"namesforevalsbasedontheplacetheywerecompiled.
#0x200
Provideinformativenamestoanonymoussubroutinesbasedontheplacetheywerecompiled.
#0x400
Savesourcecodelinesinto@{"_