Linux perl command help and examples - Computer Hope

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

"Perl" officially stands for "Practical Extraction and Report Language." It was originally a language optimized for scanning arbitrary text ... SkiptoMainContent HomeHelpLinux Linuxperlcommandoverview Updated:11/06/2021byComputerHope Aboutperl Description Syntax RunningPerl LocationsofPerl Options Environment Relatedcommands Syntax PerlDataTypes PerlSubroutines PerlOperators PerlFunctions PerlPragmas Linuxcommandshelp Aboutperl TheperlcommandistheinterpreterofthePerlprogramminglanguage. Description "Perl"officiallystandsfor"PracticalExtractionandReportLanguage."Itwasoriginallyalanguageoptimizedforscanningarbitrarytextfiles,extractinginformationfromthosetextfiles,andprintingreportsbasedonthatinformation.Itquicklybecameagoodlanguageformanysystemmanagementtasks.Overtheyears,Perlhasgrownintoageneral-purposeprogramminglanguage.It'swidelyusedforeverythingfromquick"one-liners"tofull-scaleapplicationdevelopment. Thelanguageisintendedtobepractical(easytouse,efficient,complete)ratherthanbeautiful(tiny,elegant,minimal).Itcombinessomeofthebestfeaturesofsed,awk,andsh,makingitfamiliarandeasytouseforUnixuserstowhipupquicksolutionstoannoyingproblems.Itsgeneral-purposeprogrammingfacilitiessupportprocedural,functional,andobject-orientedprogrammingparadigms,makingPerlacomfortablelanguageformajorprojects. Perl'srootsintextprocessinghaven'tbeenforgottenovertheyears.Itstillboastssomeofthemostpowerfulregularexpressionstobefoundanywhere,anditssupportforUnicodetextisworld-class.Ithandlesallkindsofstructuredtext,too,throughanextensivecollectionofextensions.Thoselibraries,collectedintheCPAN,provideready-madesolutionstoanastoundingarrayofproblems. ThePerlmottois"There'smorethanonewaytodoit." RunningPerl ThenormalwaytorunaPerlprogramisbymakingitdirectlyexecutable,orelsebypassingthenameofthesourcefileasanargumentonthecommandline.(AninteractivePerlenvironmentisalsopossible.)Uponstartup,Perllooksforyourprograminoneofthefollowingplaces: Specifiedlinebylinevia-eor-Eswitchesonthecommandline. Containedinthefilespecifiedbythefirstfilenameonthecommandline.(Notethatsystemssupportingthe#!notation,suchasbash,invokeinterpretersthisway.) Passedinimplicitlyviastandardinput.Thisworksonlyiftherearenofilenamearguments--topassargumentstoaSTDIN-readprogramyoumustexplicitlyspecifya"-"fortheprogramname. Withmethods2and3,Perlstartsparsingtheinputfilefromthebeginning,unlessyou'vespecifieda-xswitch,inwhichcaseitscansforthefirstlinestartingwith#!andcontainingtheword"perl",andstartsthereinstead.Thisisusefulforrunningaprogramembeddedinalargermessage.(Inthiscaseyouwouldindicatetheendoftheprogramusingthe__END__token.) The#!lineisalwaysexaminedforswitchesasthelineisbeingparsed.Thus,ifyou'reonamachinethatallowsonlyoneargumentwiththe#!line,orworse,doesn'tevenrecognizethe#!line,youstillcangetconsistentswitchbehaviourregardlessofhowPerlwasinvoked,evenif-xwasusedtofindthebeginningoftheprogram. Becausehistoricallysomeoperatingsystemssilentlychoppedoffkernelinterpretationofthe#!lineafter32characters,someswitchesmaybepassedinonthecommandline,andsomemaynot;youcouldevengeta"-"withoutitsletter,ifyou'renotcareful.Youprobablywanttomakesurethatallyourswitchesfalleitherbeforeorafterthat32-characterboundary.Mostswitchesdon'tactuallycareifthey'reprocessedredundantly,butgettinga"-"insteadofacompleteswitchcouldcausePerltotrytoexecutestandardinputinsteadofyourprogram.Andapartial-Iswitchcouldalsocauseoddresults. Someswitchesdocareiftheyareprocessedtwice,forinstancecombinationsof-land-0.Eitherputalltheswitchesafterthe32-characterboundary(ifapplicable),orreplacetheuseof-0digitsbyBEGIN{$/="\0digits";}. Parsingofthe#!switchesstartswherever"perl"ismentionedintheline.Thesequences"-*"and"-"arespecificallyignored. Ifthe#!linedoesnotcontaintheword"perl"northeword"indir"theprogramnamedafterthe#!isexecutedinsteadofthePerlinterpreter.Thisisslightlybizarre,butithelpspeopleonmachinesthatdon'tdo#!,becausetheycantellaprogramthattheirSHELLenvironmentvariableis/usr/bin/perl,andPerlthendispatchestheprogramtothecorrectinterpreterforthem. Afterlocatingyourprogram,Perlcompilestheentireprogramtoaninternalform.Ifthereareanycompilationerrors,executionoftheprogramisnotattempted.(Thisisunlikethetypicalshellscript,whichmightrunpart-waythroughbeforefindingasyntaxerror.) Iftheprogramissyntacticallycorrect,itisexecuted.Iftheprogramrunsofftheendwithouthittinganexit()ordie()operator,animplicitexit(0)isprovidedtoindicatesuccessfulcompletion. LocationofPerl Perlcanbelocatedwhereveryouchoose,butit'sbestforboth/usr/bin/perland/usr/local/bin/perltobesymlinkstotheactualbinary.Ifthatcan'tbedone,systemadministratorsarestronglyencouragedtoputsymlinkstoperlanditsaccompanyingutilitiesintoadirectoryoftenfoundalongauser'sPATH,orinsomeotherobviousandconvenientplace. Inthisdocumentation,#!/usr/bin/perlonthefirstlineoftheprogramstandsinforwhatevermethodworksonyoursystem.Youareadvisedtouseaspecificpathifyoucareaboutaspecificversion: #!/usr/local/bin/perl5.14 orifyouonlywanttoberunning(atleast)acertainversion,placeastatementlikethisatthetopofyourprogram: use5.014; Syntax perl[-sTtuUWX][-hv][-V[:configvar]][-cw][-d[t][:debugger]] [-D[number/list]][-pna][-Fpattern][-l[octal]] [-0[octal/hexadecimal]][-Idir][-m[-]module][-M[-]'module...'] [-f][-C[number/list]][-S][-x[dir]][-i[extension]] [[-e|-E]'command'][--][programfile][argument]... Options perlacceptsthefollowingcommand-linearguments: -0[octal/hexadecimal] specifiestheinputrecordseparator($/)asanoctalorhexadecimalnumber.Iftherearenodigits,thenullcharacteristheseparator.Otherswitchesmayprecedeorfollowthedigits.Forexample,ifyouhaveaversionoffindwhichcanprintfilenamesterminatedbythenullcharacter,youcansaythis:find.-name'*.orig'-print0|perl-n0eunlinkThespecialvalue00causesPerlto"slurp"filesinparagraphmode.Anyvalue0400orabovecausesPerltoslurpfileswhole,butbyconventionthevalue0777istheonenormallyusedforthispurpose.Youcanalsospecifytheseparatorcharacterusinghexadecimalnotation:-0xHHH...,wheretheHarevalidhexadecimaldigits.Unliketheoctalform,thisonemaybeusedtospecifyanyUnicodecharacter,eventhosebeyond0xFF.Soifyoureallywantarecordseparatorof0777,specifyitas-0x1FF.(Thismeansthatyoucannotusethe-xoptionwithadirectorynamethatconsistsofhexadecimaldigits,orelsePerlthinksyouhavespecifiedahexnumberto-0.) -a turnsonautosplitmodewhenusedwitha-nor-p.Animplicitsplitcommandtothe@Farrayisdoneasthefirstthinginsidetheimplicitwhileloopproducedbythe-nor-p.perl-ane'printpop(@F),"\n";'isequivalenttowhile(<>){@F=split('');printpop(@F),"\n";}Analternatedelimitermaybespecifiedusing-F. -C[number/list] The-CflagcontrolssomeofthePerlUnicodefeatures.Asof5.8.1,the-Ccanbefollowedeitherbyanumberoralistofoptionletters.Theletters,theirnumericvalues,andeffectsareasfollows;listingthelettersisequaltosummingthenumbers. letter number description I 1 STDINisassumedtobeinUTF-8 O 2 STDOUTisinUTF-8 E 4 STDERRisinUTF-8 S 7 I+O+E i 8 UTF-8isthedefaultPerlIOlayerforinputstreams o 16 UTF-8isthedefaultPerlIOlayerforoutputstreams D 24 i+o A 32 the@ARGVelementsareexpectedtobestringsencodedinUTF-8 L 64 normallythe"IOEioA"areunconditional,theLmakesthemconditionalonthelocaleenvironmentvariables(theLC_ALL,LC_TYPE,andLANG,intheorderofdecreasingprecedence)--ifthevariablesindicateUTF-8,thentheselected"IOEioA"areineffect a 256 Set${^UTF8CACHE}to-1,toruntheUTF-8cachingcodeindebuggingmode. Forexample,-COEand-C6bothturnonUTF-8-nessonbothSTDOUTandSTDERR.Repeatinglettersisredundant,notcumulativenortoggling. Theiooptionsmeanthatanysubsequentopen()(orsimilarI/Ooperations)inthecurrentfilescopehasthe:utf8PerlIOlayerimplicitlyappliedtothem,inotherwords,UTF-8isexpectedfromanyinputstream,andUTF-8isproducedtoanyoutputstream.Thisisonlythedefault,withexplicitlayersinopen()andwithbinmode()onecanmanipulatestreamsasusual. -Conitsown(notfollowedbyanynumberoroptionlist),ortheemptystring""forthePERL_UNICODEenvironmentvariable,hasthesameeffectas-CSDL.Inotherwords,thestandardI/Ohandlesandthedefaultopen()layerareUTF-8-fiedbutonlyifthelocaleenvironmentvariablesindicateaUTF-8locale.Thisbehaviourfollowstheimplicit(andproblematic)UTF-8behaviourofPerl5.8.0.(SeeUTF-8nolongerdefaultunderUTF-8localesinperl581delta.) Youcanuse-C0(or"0"forPERL_UNICODE)toexplicitlydisablealltheaboveUnicodefeatures. Theread-onlymagicvariable${^UNICODE}reflectsthenumericvalueofthissetting.ThisvariableissetduringPerlstartupandisafterthatread-only.Ifyouwantruntimeeffects,usethethree-argopen(),thetwo-argbinmode(),andtheopenpragma. (InPerlsearlierthan5.8.1the-CswitchwasaWin32-onlyswitchthatenabledtheuseofUnicode-aware"widesystemcall"Win32APIs.Thisfeaturewaspracticallyunused,however,andthecommandlineswitchwastherefore"recycled".) Note:Sinceperl5.10.1,ifthe-Coptionisusedonthe#!line,itmustbespecifiedonthecommandlineaswellsincethestandardstreamsarealreadysetupatthispointintheexecutionoftheperlinterpreter.Youcanalsousebinmode()tosettheencodingofanI/Ostream. -c causesPerltocheckthesyntaxoftheprogramandthenexitwithoutexecutingit.Actually,itexecutesandBEGIN,UNITCHECK,orCHECKblocksandanyusestatements:theseareconsideredasoccurringoutsidetheexecutionofyourprogram.INITandENDblocks,however,isskipped. -d,-dt runstheprogramunderthePerldebugger(perldebug).Iftisspecified,itindicatestothedebuggerthatthreadsisusedinthecodebeingdebugged. -d:MOD[=bar,baz]-dt:MOD[=bar,baz] runstheprogramunderthecontrolofadebugging,profiling,ortracingmoduleinstalledasDevel::MOD.E.g.,-d:DProfexecutestheprogramusingtheDevel::DProfprofiler.Aswiththe-Mflag,optionsmaybepassedtotheDevel::MODpackagewheretheyarereceivedandinterpretedbytheDevel::MOD::importroutine.Again,like-M,use--d:-MODtocallDevel::MOD::unimportinsteadofimport.Thecomma-separatedlistofoptionsmustfollowa"="character.Iftisspecified,itindicatestothedebuggerthatthreadsusedinthecodebeingdebugged. -Dletters-Dnumber setsdebuggingflags.Towatchhowitexecutesyourprogram,use-Dtls.(ThisworksonlyifdebuggingiscompiledintoyourPerl.)Anothernicevalueis-Dx,whichlistsyourcompiledsyntaxtree.And-Drdisplayscompiledregularexpressions;theformatoftheoutputisexplainedinperldebguts.Asanalternative,specifyanumberinsteadoflistofletters(e.g.,-D14isequivalentto-Dtls): number letter description 1 p Tokenizingandparsing(withv,displaysparsestack) 2 s Stacksnapshots(withv,displaysallstacks) 4 l Context(loop)stackprocessing 8 t Traceexecution 16 o Methodandoverloadingresolution 32 c String/numericconversions 64 P Printprofilinginfo,sourcefileinputstate 128 m MemoryandSVallocation 256 f Formatprocessing 512 r Regularexpressionparsingandexecution 1024 x Syntaxtreedump 2048 u Taintingchecks 4096 U Unofficial,Userhacking(reservedforprivate,unreleaseduse) 8192 H Hashdump--usurpsvalues() 16384 X Scratchpadallocation 32768 D Cleaningup 65536 S Opslaballocation 131072 T Tokenizing 262144 R Includereferencecountsofdumpedvariables(egwhenusing-Ds) 524288 J shows,t,P-debug(don'tJumpover)onopcodeswithinpackageDB 1048576 v Verbose:useinconjunctionwithotherflags 2097152 C CopyOnWrite 4194304 A Consistencychecksoninternalstructures 8388608 q quiet-currentlyonlysuppressesthe"EXECUTING"message 16777216 M tracesmartmatchresolution 33554432 B dumpsubroutinedefinitions,includingspecialblockslikeBEGIN Alltheseflagsrequire-DDEBUGGINGwhenyoucompilethePerlexecutable(butsee:opdinDevel::Peekor'debug'modeinrewhichmaychangethis).SeetheINSTALLfileinthePerlsourcedistributionforhowtodothis.Thisflagisautomaticallysetifyouinclude-goptionwhenConfigureasksyouaboutoptimizer/debuggerflags. Ifyou'reonlytryingtogetaprintoutofeachlineofPerlcodeasitexecutes,thewaythatsh-xprovidesforshellscripts,youcan'tusePerl's-Dswitch.Insteaddothis: #Ifyouhave"env"utility envPERLDB_OPTS="NonStop=1AutoTrace=1frame=2"perl-dSprogram #Bourneshellsyntax PERLDB_OPTS="NonStop=1AutoTrace=1frame=2"perl-dSprogram #cshsyntax (setenvPERLDB_OPTS"NonStop=1AutoTrace=1frame=2";perl-dSprogram) -ecommandline maybeusedtoenteronelineofprogram.If-eisgiven,Perlwon'tlookforafilenameintheargumentlist.Multiple-ecommandsmaybegiventobuildupamulti-linescript.Makesuretousesemicolonswhereyouwouldinanormalprogram. -Ecommandline behaveslike-e,exceptthatitimplicitlyenablesalloptionalfeatures(inthemaincompilationunit). -f Disableexecuting$Config{sitelib}/sitecustomize.platstartup.Perlcanbebuiltsothatitbydefaulttriestoexecute$Config{sitelib}/sitecustomize.platstartup(inaBEGINblock).ThisisahookthatallowsthesysadmintocustomizehowPerlbehaves.Itcanforinstancebeusedtoaddentriestothe@INCarraytomakePerlfindmodulesinnon-standardlocations.Perlactuallyinsertsthefollowingcode:BEGIN{do{local$!;-f"$Config{sitelib}/sitecustomize.pl";}&&do"$Config{sitelib}/sitecustomize.pl";}Sinceitisanactualdo(notarequire),sitecustomize.pldoesn'tneedtoreturnatruevalue.Thecodeisruninpackagemain,initsownlexicalscope.However,ifthescriptdies,[email protected]won'tbeset.Thevalueof$Config{sitelib}isalsodeterminedinCcodeandnotreadfromConfig.pm,whichisnotloaded.Thecodeisexecutedveryearly.Forexample,anychangesmadeto@INCshowsupintheoutputof"perl-V".Ofcourse,ENDblocksislikewiseexecutedverylate.Todetermineatruntimeifthiscapabilityiscompiledinyourperl,youcancheckthevalueof$Config{usesitecustomize}. -Fpattern specifiesthepatterntosplitonif-aisalsoineffect.Thepatternmaybesurroundedby//,"",or'',otherwiseitisputinsinglequotes.Youcan'tuseliteralwhitespaceinthepattern. -h printsasummaryoftheoptions. -i[extension] specifiesthatfilesprocessedbythe<>constructaretobeeditedin-place.Itdoesthisbyrenamingtheinputfile,openingtheoutputfilebytheoriginalname,andselectingthatoutputfileasthedefaultforprint()statements.Theextension,ifsupplied,isusedtomodifythenameoftheoldfiletomakeabackupcopy,followingtheserules:Ifnoextensionissupplied,andyoursystemsupportsit,theoriginalfileiskeptopenwithoutanamewhiletheoutputisredirectedtoanewfilewiththeoriginal.Whenperlexits,cleanlyornot,theoriginalfileisunlinked.Iftheextensiondoesn'tcontaina*,thenitisappendedtotheendofthecurrentfilenameasasuffix.Iftheextensiondoescontainoneormore*characters,theneach*isreplacedwiththecurrentfilename.InPerlterms,youcouldthinkofthisas:($backup=$extension)=~s/\*/$file_name/g;Thisallowsyoutoaddaprefixtothebackupfile,insteadof(orinadditionto)asuffix:perl-pi'orig_*'-e's/bar/baz/'fileA#backupto'orig_fileA'Oreventoplacebackupcopiesoftheoriginalfilesintoanotherdirectory(providedthedirectoryalreadyexists):perl-pi'old/*.orig'-e's/bar/baz/'fileA#backupto'old/fileA.orig'Thesesetsofone-linersareequivalent:#overwritecurrentfileperl-pi-e's/bar/baz/'fileA#overwritecurrentfileperl-pi'*'-e's/bar/baz/'fileA#backupto'fileA.orig'perl-pi'.orig'-e's/bar/baz/'fileA#backupto'fileA.orig'perl-pi'*.orig'-e's/bar/baz/'fileAFromtheshell,sayingperl-p-i.orig-e"s/foo/bar/;..."isthesameasusingtheprogram:#!/usr/bin/perl-pi.origs/foo/bar/;whichisequivalentto#!/usr/bin/perl$extension='.orig';LINE:while(<>){if($ARGVne$oldargv){if($extension!~/\*/){$backup=$ARGV.$extension;}else{($backup=$extension)=~s/\*/$ARGV/g;}rename($ARGV,$backup);open(ARGVOUT,">$ARGV");select(ARGVOUT);$oldargv=$ARGV;}s/foo/bar/;}continue{print; #thisprintstooriginalfilename}select(STDOUT);exceptthatthe-iformdoesn'tneedtocompare$ARGVto$oldargvtoknowwhenthefilenamehaschanged.Itdoes,however,useARGVOUTfortheselectedfilehandle.NotethatSTDOUTisrestoredasthedefaultoutputfilehandleaftertheloop.Asshownabove,Perlcreatesthebackupfilewhetherornotanyoutputisactuallychanged.Sothisisafancywaytocopyfiles:perl-p-i'/some/file/path/*'-e1file1file2file3...orperl-p-i'.orig'-e1file1file2file3...Youcanuseeofwithoutparenthesestolocatetheendofeachinputfile,incaseyouwanttoappendtoeachfile,orresetlinenumbering.If,foragivenfile,Perlisunabletocreatethebackupfileasspecifiedintheextensionthenitskipsthatfileandcontinueonwiththenextone(ifitexists).Youcannotuse-itocreatedirectoriesortostripextensionsfromfiles.Perldoesnotexpand~infilenames,whichisgoodsincesomefolksuseitfortheirbackupfiles:perl-pi~-e's/foo/bar/'file1file2file3...Notethatbecause-irenamesordeletestheoriginalfilebeforecreatinganewfileofthesamename,Unix-stylesoftandhardlinkswon'tbepreserved.Finally,the-iswitchdoesnotimpedeexecutionwhennofilesaregivenonthecommandline.Inthiscase,nobackupismade(theoriginalfilecannot,ofcourse,bedetermined)andprocessingproceedsfromSTDINtoSTDOUTasmightbeexpected. -Idirectory Directoriesspecifiedby-Iareprependedtothesearchpathformodules(@INC). -l[octnum] enablesautomaticline-endingprocessing.Ithastwoseparateeffects.First,itautomaticallychomps$/(theinputrecordseparator)whenusedwith-nor-p.Second,itassigns$\(theoutputrecordseparator)tohavethevalueofoctnumsothatanyprintstatementshasthatseparatoraddedbackon.Ifoctnumisomitted,sets$\tothecurrentvalueof$/.Forinstance,totrimlinesto80columns:perl-lpe'substr($_,80)=""'Notethattheassignment$\=$/isdonewhentheswitchisprocessed,sotheinputrecordseparatorcanbedifferentthantheoutputrecordseparatorifthe-lswitchisfollowedbya-0switch:gnufind/-print0|perl-ln0e'print"found$_"if-p'Thissets$\tonewlineandthensets$/tothenullcharacter. -m[-]module-M[-]module-M[-]'module...'-[mM][-]module=arg[,arg]... -mmoduleexecutesusemodule();beforeexecutingyourprogram.-Mmoduleexecutesusemodule;beforeexecutingyourprogram.Youcanusequotestoaddextracodeafterthemodulename,e.g.,'-MMODULEqw(foobar)'.Ifthefirstcharacterafterthe-Mor-misadash(-)thenthe'use'isreplacedwith'no'.Youcanalsosay-mMODULE=foo,baror-MMODULE=foo,barasashortcutfor'-MMODULEqw(foobar)'.Thisavoidstheneedtousequoteswhenimportingsymbols.Theactualcodegeneratedby-MMODULE=foo,barisusemodulesplit(/,/,q{foo,bar}).Notethatthe=formremovesthedistinctionbetween-mand-M.Aconsequenceofthisisthat-MMODULE=numberneverdoesaversioncheck,unlessMODULE::import()itselfissetuptodoaversioncheck,whichcouldhappenforexampleifMODULEinheritsfromExporter. -n causesPerltoassumethefollowinglooparoundyourprogram,whichmakesititerateoverfilenameargumentssomewhatlikesed-norawk:LINE:while(<>){...#yourprogramgoeshere}Notethatthelinesarenotprintedbydefault.See-ptohavelinesprinted.Ifafilenamedbyanargumentcannotbeopenedforsomereason,Perlwarnsyouaboutitandmovesontothenextfile.Also,notethat<>passescommandlineargumentstoopen,whichdoesn'tnecessarilyinterpretthemasfilenames.Hereisanefficientwaytodeleteallfilesthathaven'tbeenmodifiedforatleastaweek:find.-mtime+7-print|perl-nleunlinkThisisfasterthanusingthe-execswitchoffindbecauseyoudon'thavetostartaprocessoneveryfilenamefound.Itdoessufferfromthebugofmishandlingnewlinesinpathnames,whichyoucanfixifyoufollowtheexampleunder-0.BEGINandENDblocksmaybeusedtocapturecontrolbeforeoraftertheimplicitprogramloop,asinawk. -p causesPerltoassumethefollowinglooparoundyourprogram,whichmakesititerateoverfilenameargumentssomewhatlikesed:LINE:while(<>){...#yourprogramgoeshere}continue{printordie"-pdestination:$!\n";}Ifafilenamedbyanargumentcannotbeopenedforsomereason,Perlwarnsyouaboutit,andmovesontothenextfile.Notethatthelinesareprintedautomatically.Anerroroccurringduringprintingistreatedasfatal.Tosuppressprintingusethe-nswitch.A-poverridesa-nswitch.BEGINandENDblocksmaybeusedtocapturecontrolbeforeoraftertheimplicitloop,asinawk. -s enablesrudimentaryswitchparsingforswitchesonthecommandlineaftertheprogramnamebutbeforeanyfilenamearguments(orbeforeanargumentof"--").Anyswitchfoundthereisremovedfrom@ARGVandsetsthecorrespondingvariableinthePerlprogram.Thefollowingprogramprints"1"iftheprogramisinvokedwitha-xyzswitch,and"abc"ifitisinvokedwith-xyz=abc.#!/usr/bin/perl-sif($xyz){print"$xyz\n"}Donotethataswitchlike--helpcreatesthevariable${-help},whichisnotcompliantwithusestrict"refs".Also,whenusingthisoptiononascriptwithwarningsenabledyoumaygetalotofspurious"usedonlyonce"warnings. -S makesPerlusethePATHenvironmentvariabletosearchfortheprogramunlessthenameoftheprogramcontainspathseparators.Onsomeplatforms,thisalsomakesPerlappendsuffixestothefilenamewhilesearchingforit.Forexample,onWin32platforms,the".bat"and".cmd"suffixesareappendedifalookupfortheoriginalnamefails,andifthenamedoesnotalreadyendinoneofthosesuffixes.IfyourPerlwascompiledwithDEBUGGINGturnedon,usingthe-DpswitchtoPerlshowshowthesearchprogresses.oftenthisisusedtoemulate#!startuponplatformsthatdon'tsupport#!.It'salsoconvenientwhendebuggingascriptthatuses#!,andisthusnormallyfoundbytheshell's$PATHsearchmechanism.ThisexampleworksonmanyplatformsthathaveashellcompatiblewithBourneshell:#!/usr/bin/perleval'exec/usr/bin/perl-wS$0${1+"[email protected]"}'if$running_under_some_shell;Thesystemignoresthefirstlineandfeedstheprogramto/bin/sh,whichproceedstotrytoexecutethePerlprogramasashellscript.Theshellexecutesthesecondlineasanormalshellcommand,andthusstartsupthePerlinterpreter.Onsomesystems$0doesn'talwayscontainthefullpathname,sothe-StellsPerltosearchfortheprogramifnecessary.AfterPerllocatestheprogram,itparsesthelinesandignoresthembecausethevariable$running_under_some_shellisnevertrue.Iftheprogramisinterpretedbycsh,youneedtoreplace${1+"[email protected]"}with$*,eventhoughthatdoesn'tunderstandembeddedspaces(andsuch)intheargumentlist.Tostartupshratherthancsh,somesystemsmayhavetoreplacethe#!linewithalinecontainingonlyacolon,whichispolitelyignoredbyPerl.Othersystemscan'tcontrolthat,andneedatotallydeviousconstructthatworksunderanyofcsh,sh,orperl,suchasthefollowing:eval'(exit$?0)'&&eval'execperl-wS$0${1+"[email protected]"}'&eval'exec/usr/bin/perl-wS$0$argv:q'if$running_under_some_shell;Ifthefilenamesuppliedcontainsdirectoryseparators(andsoisanabsoluteorrelativepathname),andifthatfileisnotfound,platformsthatappendfileextensionsdosoandtrytolookforthefilewiththoseextensionsadded,onebyone.OnDOS-likeplatforms,iftheprogramdoesnotcontaindirectoryseparators,itisfirstsearchedforinthecurrentdirectorybeforebeingsearchedforonthePATH.OnUnixplatforms,theprogramissearchedforstrictlyonthePATH. -t Like-T,buttaintchecksissuewarningsratherthanfatalerrors.Thesewarningscannowbecontrollednormallywithnowarningsqw(taint).Note:Thisisnotasubstitutefor-T!Thisistoonlybeusedasatemporarydevelopmentaidwhilesecuringlegacycode:forrealproductioncodeandfornewsecurecodewrittenfromscratch,alwaysusethereal-T. -T turnson"taint"soyoucantestthem.Ordinarilythesechecksaredoneonlywhenrunningsetuidorsetgid.It'sagoodideatoturnthemonexplicitlyforprogramsthatrunonbehalfofsomeoneelsewhomyoumightnotnecessarilytrust,suchasCGIprogramsoranyInternetserversyoumightwriteinPerl.Forsecurityreasons,thisoptionmustbeseenbyPerlquiteearly;usuallythismeansitmustappearearlyonthecommandlineorinthe#!lineforsystemswhichsupportthatconstruct. -u ThisswitchcausesPerltodumpcoreaftercompilingyourprogram.Youcanthenintheorytakethiscoredumpandturnitintoanexecutablefileusingtheundumpprogram.Thisspeedsstartupattheexpenseofsomediskspace(whichyoucanminimizebystrippingtheexecutable).Ifyouwanttoexecuteaportionofyourprogrambeforedumping,usethedump()operatorinstead.Note:availabilityofundumpisplatformspecific. -U allowsPerltodounsafeoperations.Currentlytheonly"unsafe"operationsareattemptingtounlinkdirectorieswhilerunningassuperuserandrunningsetuidprogramswithfataltaintchecksturnedintowarnings.Notethatwarningsmustbeenabledwiththisoptiontoactuallygeneratethetaint-checkwarnings. -v printstheversionandpatchlevelofyourperlexecutable. -V printssummaryofthemajorperlconfigurationvaluesandthecurrentvaluesof@INC. -V:configvar PrintstoSTDOUTthevalueofthenamedconfigurationvariable(s),withmultipleswhenyourconfigvarargumentlookslikearegex(hasnon-letters).Forexample:perl-V:libclibc='/lib/libc-2.2.4.so';perl-V:lib.libs='-lnsl-lgdbm-ldb-ldl-lm-lcrypt-lutil-lc';libc='/lib/libc-2.2.4.so';perl-V:lib.*libpth='/usr/local/lib/lib/usr/lib';libs='-lnsl-lgdbm-ldb-ldl-lm-lcrypt-lutil-lc';lib_ext='.a';libc='/lib/libc-2.2.4.so';libperl='libperl.a';....Additionally,extracolonscanbeusedtocontrolformatting.Atrailingcolonsuppressesthelinefeedandterminator";",allowingyoutoembedqueriesintoshellcommands.(mnemonic:PATHseparator":".)echo"compression-vars:"`perl-V:z.*:`"arehere!"compression-vars:zcat=''zip='zip'arehere!Aleadingcolonremovesthe"name="partoftheresponse,thisallowsyoutomaptothenameyouneed.(mnemonic:emptylabel)echo"goodvfork="`./perl-Ilib-V::usevfork`goodvfork=false;Leadingandtrailingcolonscanbeusedtogetherifyouneedpositionalparametervalueswithoutthenames.Notethatinthecasebelow,thePERL_APIparametersarereturnedinalphabeticalorder.echobuilding_on`perl-V::osname:-V::PERL_API_.*:`nowbuilding_on'linux''5''1''9'now -w printswarningsaboutdubiousconstructs,suchasvariablenamesmentionedonlyonceandscalarvariablesusedbeforebeingset;redefinedsubroutines;referencestoundefinedfilehandles;filehandlesopenedread-onlythatyouareattemptingtowriteon;valuesusedasanumberthatdon'tlooklikenumbers;usinganarrayasthoughitwereascalar;ifyoursubroutinesrecursemorethan100deep;andinnumerableotherthings.Thisswitchreallyonlyenablestheglobal$^Wvariable;normally,thelexicallyscopedusewarningspragmaispreferred.Youcandisableorpromoteintofatalerrorsspecificwarningsusing__WARN__hooks,asdescribedinperlvarandwarn.Seealsoperldiagandperltrap.Afine-grainedwarningfacilityisalsoavailableifyouwanttomanipulateentireclassesofwarnings. -W Enablesallwarningsregardlessofnowarningsor$^W. -X Disablesallwarningsregardlessofusewarningsor$^W. -x-xdirectory tellsPerlthattheprogramisembeddedinalargerchunkofunrelatedtext,suchasinamailmessage.Leadinggarbageisdiscardeduntilthefirstlinethatstartswith#!andcontainsthestring"perl".Anymeaningfulswitchesonthatlineareapplied.Allreferencestolinenumbersbytheprogram(warnings,errors,...)treatthe#!lineasthefirstline.Thusawarningonthe2ndlineoftheprogram,whichisonthe100thlineinthefile,isreportedasline2,notasline100.Thiscanbeoverriddenusingthe#linedirective.Ifadirectorynameisspecified,Perlswitchestothatdirectorybeforerunningtheprogram.The-xswitchcontrolsonlythedisposalofleadinggarbage.Theprogrammustbeterminatedwith__END__ifthereistrailinggarbagetobeignored;theprogramcanprocessanyorallofthetrailinggarbageviatheDATAfilehandleifdesired.Thedirectory,ifspecified,mustappearimmediatelyfollowingthe-xwithnointerveningwhitespace. Environment Thefollowingenvironmentvariablesaffecttheoperationofperl: HOME Usedifchdirhasnoargument. LOGDIR UsedifchdirhasnoargumentandHOMEisnotset. PATH Usedinexecutingsubprocesses,andinfindingtheprogramif-Sisused. PERL5LIB AlistofdirectoriesinwhichtolookforPerllibraryfilesbeforelookinginthestandardlibraryandthecurrentdirectory.Anyarchitecture-specificandversion-specificdirectories,suchasversion/archname/,version/,orarchname/underthespecifiedlocationsareautomaticallyincludediftheyexist,withthislookupdoneatinterpreterstartuptime.Also,anydirectoriesmatchingtheentriesin$Config{inc_version_list}areadded.(Theseoftenwouldbeforoldercompatibleperlversionsinstalledinthesamedirectorytree.)IfPERL5LIBisnotdefined,PERLLIBisused.Directoriesareseparated(likeinPATH)byacolononUnix-likeplatformsandbyasemicolononWindows(theproperpathseparatorbeinggivenbythecommandperl-V:path_sep).Whenrunningtaintchecks,eitherbecausetheprogramwasrunningsetuidorsetgid,orthe-Tor-tswitchwasspecified,neitherPERL5LIBnorPERLLIBisconsulted.Theprogramshouldinsteadsay:uselib"/my/directory"; PERL5OPT Command-lineoptions(switches).SwitchesinthisvariablearetreatedasiftheywereoneveryPerlcommandline.Onlythe-[CDIMUdmtwW]switchesareallowed.Whenrunningtaintchecks(eitherbecausetheprogramwasrunningsetuidorsetgid,orbecausethe-Tor-tswitchwasused),thisvariableisignored.IfPERL5OPTbeginswith-T,taintingenabledandsubsequentoptionsignored.IfPERL5OPTbeginswith-t,taintingenabled,awritabledotremovedfrom@INC,andsubsequentoptionshonored. PERLIO Aspace(orcolon)separatedlistofPerlIOlayers.IfperlisbuilttousePerlIOsystemforIO(thedefault)theselayersaffectPerl'sIO.Itisconventionaltostartlayernameswithacolon(forexample,:perlio)toemphasizetheirsimilaritytovariable"attributes".Butthecodethatparseslayerspecificationstrings,whichisalsousedtodecodethePERLIOenvironmentvariable,treatsthecolonasaseparator.AnunsetoremptyPERLIOisequivalenttothedefaultsetoflayersforyourplatform;forexample,:unix:perlioonUnix-likesystemsand:unix:crlfonWindowsandotherDOS-likesystems.ThelistbecomesthedefaultforallPerl'sIO.Consequentlyonlybuilt-inlayerscanappearinthislist,asexternallayers(suchas:encoding())needIOtoloadthem.Seeopenpragmaforhowtoaddexternalencodingsasdefaults.LayersthatmakesensetoincludeinthePERLIOenvironmentvariablearebrieflysummarizedbelow.FormoredetailsseePerlIO. :bytes Apseudolayerthatturnsthe:utf8flagoffforthelayerbelow;unlikelytobeusefulonitsownintheglobalPERLIOenvironmentvariable.Youperhapswerethinkingof:crlf:bytesor:perlio:bytes. :crlf AlayerwhichdoesCRLFto"\n"translationdistinguishing"text"and"binary"filesinthemannerofMS-DOSandsimilaroperatingsystems.(ItcurrentlydoesnotmimicMS-DOSasfarastreatingofControl-Zasbeinganend-of-filemarker.) :mmap Alayerthatimplements"reading"offilesusingmmaptomakeanentirefileappearintheprocess'saddressspace,andthenusingthatasPerlIO's"buffer". :perlio Thisisare-implementationofstdio-likebufferingwrittenasaPerlIOlayer.Assuch,itcallswhateverlayerisbelowitforitsoperations,often:unix. :pop Anexperimentalpseudolayerthatremovesthetopmostlayer.Usewiththesamecareasisreservedfornitroglycerin. :raw Apseudolayerthatmanipulatesotherlayers.Applyingthe:rawlayerisequivalenttocallingbinmode($fh).Itmakesthestreampasseachbyteas-iswithouttranslation.Inparticular,bothCRLFtranslationandintuiting:utf8fromthelocalearedisabled.UnlikeinearlierversionsofPerl,:rawisnotonlytheinverseof:crlf:otherlayerswhichwouldaffectthebinarynatureofthestreamarealsoremovedordisabled. :stdio ThislayerprovidesaPerlIOinterfacebywrappingsystem'sANSIC"stdio"librarycalls.ThelayerprovidesbothbufferingandIO.Notethatthe:stdiolayerdoesnotdoCRLFtranslationevenifthatistheplatform'snormalbehaviour.Youneeda:crlflayeraboveittodothat. :unix Low-levellayerthatcallsread,write,lseek,etc. :utf8 ApseudolayerthatenablesaflaginthelayerbelowtotellPerlthatoutputshouldbeinutf8andthatinputshouldberegardedasalreadyinvalidutf8form.WARNING:Itdoesnotcheckforvalidityandassuchshouldbehandledwithextremecautionforinput,becausesecurityviolationscanoccurwithnon-shortestUTF-8encodings,etc.Generally:encoding(utf8)isthebestoptionwhenreadingUTF-8encodeddata. :win32 OnWin32platformsthisexperimentallayerusesnative"handle"IOratherthanaUnix-likenumericfiledescriptorlayer.Knowntobebuggyinrelease5.14. Thedefaultsetoflayersshouldgiveacceptableresultsonallplatforms. ForUnixplatformsthataretheequivalentof"unixperlio"or"stdio".Configureissetuptopreferthe"stdio"implementationifthesystem'slibraryprovidesforfastaccesstothebuffer;otherwise,itusesthe"unixperlio"implementation. OnWin32thedefaultinthisrelease(5.14)is"unixcrlf".Win32's"stdio"hassomebugs/mis-featuresforPerlIOwhicharesomewhatdependingontheversionandvendoroftheCcompiler.Usingourowncrlflayerasthebufferavoidsthoseissuesandmakesthingsmoreuniform.ThecrlflayerprovidesCRLFconversionandbuffering. Thecurrentrelease(5.14asofthiswriting)usesunixasthebottomlayeronWin32,andsostillusestheCcompiler'snumericfiledescriptorroutines.Thereisanexperimentalnativewin32layer,whichisexpectedtobeenhancedandshouldeventuallybecomethedefaultunderWin32. ThePERLIOenvironmentvariableiscompletelyignoredwhenPerlisrunintaintmode. PERLIO_DEBUG Ifsettothenameofafileordevice,certainoperationsofPerlIOsubsystemisloggedtothatfile,whichisopenedinappendmode.TypicalusesareinUnix:envPERLIO_DEBUG=/dev/ttyperlscript...andunderWin32,theapproximatelyequivalent:setPERLIO_DEBUG=CONperlscript...Thisfunctionalityisdisabledforsetuidscriptsandforscriptsrunwith-T. PERLLIB AlistofdirectoriesinwhichtolookforPerllibraryfilesbeforelookinginthestandardlibraryandthecurrentdirectory.IfPERL5LIBisdefined,PERLLIBisnotused.ThePERLLIBenvironmentvariableiscompletelyignoredwhenPerlisrunintaintmode. PERL5DB Thecommandusedtoloadthedebuggercode.Thedefaultis:BEGIN{require"perl5db.pl"}ThePERL5DBenvironmentvariableisonlyusedwhenPerlisstartedwithabare-dswitch. PERL5DB_THREADED Ifsettoatruevalue,indicatestothedebuggerthatthecodebeingdebuggedusesthreads. PERL5SHELL (specifictotheWin32port.)OnWin32portsonly,maybesettoanalternativeshellthatPerlmustuseinternallyforexecuting"backtick"commandsorsystem().Defaultiscmd.exe/x/d/conWindowsNTandcommand.com/conWindows95.Thevalueisconsideredspace-separated.Precedeanycharacterthatneedstobeprotected,likeaspaceorbackslash,withanotherbackslash.NotethatPerldoesn'tuseCOMSPECforthispurposebecauseCOMSPEChasahighdegreeofvariabilityamongusers,leadingtoportabilityconcerns.Besides,Perlcanuseashellthatmaynotbefitforinteractiveuse,andsettingCOMSPECtosuchashellmayinterferewiththeproperfunctioningofotherprograms(whichusuallylookinCOMSPECtofindashellfitforinteractiveuse).BeforePerl5.10.0and5.8.8,PERL5SHELLwasnottaintcheckedwhenrunningexternalcommands.Itisrecommendedthatyouexplicitlyset(ordelete)$ENV{PERL5SHELL}whenrunningintaintmodeunderWindows. PERL_ALLOW_NON_IFS_LSP (specifictotheWin32port.)Setto1toallowtheuseofnon-IFScompatibleLSPs(LayeredServiceProviders).PerlnormallysearchesforanIFS-compatibleLSPbecausethisisrequiredforitsemulationofWindowssocketsasrealfilehandles.However,thismaycauseproblemsifyouhaveafirewallsuchasMcAfeeGuardian,whichrequiresthatallapplicationsuseitsLSPbutthatisnotIFS-compatible,becauseclearlyPerlnormallyavoidsusingsuchanLSP.Settingthisenvironmentvariableto1meansthatPerlusesthefirstsuitableLSPenumeratedinthecatalog,whichkeepsMcAfeeGuardianhappy,andinthatparticularcasePerlstillworkstoobecauseMcAfeeGuardian'sLSPactuallyplaysothergameswhichallowapplicationsrequiringIFScompatibilitytowork. PERL_DEBUG_MSTATS RelevantonlyifPerliscompiledwiththemallocincludedwiththePerldistribution;thatis,ifperl-V:d_mymallocis"define".Ifset,thisdumpsoutmemorystatisticsafterexecution.Ifsettoanintegergreaterthanone,alsodumpsoutmemorystatisticsaftercompilation. PERL_DESTRUCT_LEVEL RelevantonlyifyourPerlexecutablewasbuiltwith-DDEBUGGING,thiscontrolsthebehaviourofglobaldestructionofobjectsandotherreferences. PERL_DL_NONLAZY Setto"1"tohavePerlresolveallundefinedsymbolswhenitloadsadynamiclibrary.Thedefaultbehaviouristoresolvesymbolswhentheyareused.Settingthisvariableisusefulduringtestingofextensions,asitensuresthatyougetanerroronmisspelledfunctionnamesevenifthetestsuitedoesn'tcallthem. PERL_ENCODING Ifusingtheuseencodingpragmawithoutanexplicitencodingname,thePERL_ENCODINGenvironmentvariableisconsultedforanencodingname. PERL_HASH_SEED (SincePerl5.8.1,newsemanticsinPerl5.18.0)UsedtooverridetherandomizationofPerl'sinternalhashfunction.Thevalueisexpressedinhexadecimal,andmayincludealeading0x.Truncatedpatternsaretreatedasthoughtheyaresuffixedwithsufficient0'sasrequired.Iftheoptionisprovided,andPERL_PERTURB_KEYSisNOTset,thenavalueof'0'impliesPERL_PERTURB_KEYS=0andanyothervalueimpliesPERL_PERTURB_KEYS=2.PLEASENOTE:Thehashseedissensitiveinformation.HashesarerandomizedtoprotectagainstlocalandremoteattacksagainstPerlcode.Bymanuallysettingaseed,thisprotectionmaybepartiallyorcompletelylost. PERL_PERTURB_KEYS (SincePerl5.18.0)Setto"0"or"NO"thentraversingkeysisrepeatablefromruntorunforthesamePERL_HASH_SEED.Insertionintoahashwon'tchangetheorder,excepttoprovideformorespaceinthehash.WhencombinedwithsettingPERL_HASH_SEED,thismodeisasclosetopre5.18behaviorasyoucanget.Whensetto"1"or"RANDOM"thentraversingkeysisrandomized.Everytimeahashisinsertedintothekeyorderchangesinarandomfashion.TheordermaynotberepeatableinafollowingprogramrunevenifthePERL_HASH_SEEDwasspecified.Thisisthedefaultmodeforperl.Whensetto"2"or"DETERMINISTIC"theninsertingkeysintoahashcausesthekeyordertochange,butinawaythatisrepeatablefromprogramruntoprogramrun.NOTE:Useofthisoptionisconsideredinsecure,andisintendedonlyfordebuggingnon-deterministicbehaviorinPerl'shashfunction.Donotuseitinproduction. PERL_HASH_SEED_DEBUG (SincePerl5.8.1.)Setto"1"todisplay(toSTDERR)informationaboutthehashfunction,seed,andwhattypeofkeytraversalrandomizationisineffectatthebeginningofexecution.This,combinedwithPERL_HASH_SEEDandPERL_PERTURB_KEYSisintendedtoaidindebuggingnondeterministicbehaviourcausedbyhashrandomization.Notethatanyinformationaboutthehashfunction,especiallythehashseedissensitiveinformation:byknowingit,onecancraftadenial-of-serviceattackagainstPerlcode,evenremotely.Donotdisclosethehashseedtopeoplewhodon'tneedtoknowit.Seealsohash_seed()andkey_traversal_mask()inHash::Util.Anexampleoutputmightbe:HASH_FUNCTION=ONE_AT_A_TIME_HARDHASH_SEED=0x652e9b9349a7a032PERTURB_KEYS=1(RANDOM) PERL_MEM_LOG IfyourPerlwasconfiguredwith-Accflags=-DPERL_MEM_LOG,settingtheenvironmentvariablePERL_MEM_LOGenablesloggingdebugmessages.Thevaluehastheform[m][s][t],wherenumberisthefiledescriptornumberyouwanttowriteto(2isdefault),andthecombinationoflettersspecifiesthatyouwantinformationabout(m)emoryand/or(s)v,optionallywith(t)imestamps.Forexample,PERL_MEM_LOG=1mstlogsallinformationtostdout.Youcanwritetootheropenedfiledescriptorsinavarietyofways:$3>foo3PERL_MEM_LOG=3mperl... PERL_ROOT (specifictotheVMSport.)Atranslation-concealedrootedlogicalnamewithPerlandthelogicaldeviceforthe@INCpathonVMSonly.OtherlogicalnamesthataffectPerlonVMSincludePERLSHR,PERL_ENV_TABLES,andSYS$TIMEZONE_DIFFERENTIAL,butareoptionalanddiscussedfurtherinperlvmsandinREADME.vmsinthePerlsourcedistribution. PERL_SIGNALS AvailableinPerls5.8.1andlater.Ifsetto"unsafe",thepre-Perl-5.8.0signalbehaviour(whichisimmediatebutunsafe)isrestored.Ifsettosafe,thensafe(butdeferred)signalsareused. PERL_UNICODE Equivalenttothe-Ccommand-lineswitch.Notethatthisisnotabooleanvariable.Settingthisto"1"isnottherightwayto"enableUnicode".Youcanuse"0"to"disableUnicode",though(oralternativelyunsetPERL_UNICODEinyourshellbeforestartingPerl).Seethedescriptionofthe-Cswitchformoreinformation. SYS$LOGIN (specifictotheVMSport.)UsedifchdirhasnoargumentandHOMEandLOGDIRarenotset. Perlanditsvariousmodulesandcomponents,includingitstestframeworks,maysometimesmakeuseofcertainotherenvironmentvariables.Someofthesearespecifictoaparticularplatform.Pleaseconsulttheappropriatemoduledocumentationandanydocumentationforyourplatformforvariablespeculiartothosespecificsituations. Perlmakesallenvironmentvariablesavailabletotheprogrambeingexecuted,andpassesthesealongtoanychildprocessesitstarts.However,programsrunningsetuidwoulddowelltoexecutethefollowinglinesbeforedoinganythingelse,onlytokeeppeoplehonest: $ENV{PATH}="/bin:/usr/bin";#orwhateveryouneed $ENV{SHELL}="/bin/sh"ifexists$ENV{SHELL}; delete@ENV{qw(IFSCDPATHENVBASH_ENV)}; Alsosee: SyntaxPerlDataTypesPerlSubroutinesPerlOperatorsPerlFunctionsPerlPragmas Relatedcommands awk—InterpreterfortheAWKtextprocessingprogramminglanguage.sed—Autilityforfilteringandtransformingtext. Wasthispageuseful?YesNoFeedbackE-mailSharePrint



請為這篇文章評分?