Processing command line arguments - @ARGV in Perl

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

Perl automatically provides an array called @ARGV, that holds all the values from the command line. You don't have to declare the variable, even ... Togglenavigation PerlMaven PerlTutorial Pro Login Register Books Typekeyword: Archive About Perltutorial Introduction InstallingandgettingstartedwithPerl TheHash-bangline,orhowtomakeaPerlscriptsexecutableonLinux PerlEditor HowtogetHelpforPerl? Perlonthecommandline CorePerldocumentationandCPANmoduledocumentation POD-PlainOldDocumentation DebuggingPerlscripts Scalars CommonWarningsandErrormessagesinPerl Prompt,readfromSTDIN,readfromthekeyboardinPerl AutomaticstringtonumberconversionorcastinginPerl Conditionalstatements,usingif,else,elsifinPerl BooleanvaluesinPerl Numericaloperators Stringoperators:concatenation(.),repetition(x) undef,theinitialvalueandthedefinedfunctionofPerl StringsinPerl:quoted,interpolatedandescaped Heredocuments,orhowtocreatemulti-linestringsinPerl Scalarvariables ComparingscalarsinPerl Stringfunctions:length,lc,uc,index,substr NumberGuessinggame whileloop ScopeofvariablesinPerl Short-circuitinbooleanexpressions Files HowtoexitfromaPerlscript? Standardoutput,standarderrorandcommandlineredirection Warningwhensomethinggoeswrong Whatdoesdiedo? WritingtofileswithPerl Appendingtofiles Openandreadfromtextfiles Don'tOpenFilesintheoldway ReadingandwritingbinaryfilesinPerl EOF-EndoffileinPerl tellhowfarhavewereadafile seek-movethepositioninthefilehandleinPerl slurpmode-readingafileinonestep ListsandArrays Perlforloopexplainedwithexamples PerlArrays Processingcommandlinearguments-@ARGVinPerl HowtoprocesscommandlineargumentsinPerlusingGetopt::Long AdvancedusageofGetopt::Longforacceptingcommandlinearguments Perlsplit-tocutupastringintopieces HowtoreadaCSVfileusingPerl? join Theyearof19100 ScalarandListcontextinPerl,thesizeofanarray Readingfromafileinscalarandlistcontext STDINinscalarandlistcontext SortingarraysinPerl Sortingmixedstrings UniquevaluesinanarrayinPerl ManipulatingPerlarrays:shift,unshift,push,pop ReversePolishCalculatorinPerlusingastack UsingaqueueinPerl Reverseanarray,astringoranumber TheternaryoperatorinPerl Loopcontrols:next,last,continue,break min,max,suminPerlusingList::Util qw-quoteword Subroutines SubroutinesandfunctionsinPerl PassingmultipleparameterstoafunctioninPerl VariablenumberofparametersinPerlsubroutines ReturningmultiplevaluesoralistfromasubroutineinPerl Understandingrecursivesubroutines-traversingadirectorytree Hashes HashesinPerl CreatingahashfromanarrayinPerl Perlhashinscalarandlistcontext exists-checkifakeyexistsinahash deleteanelementfromahash HowtosortahashinPerl? CountthefrequencyofwordsintextusingPerl RegularExpressions IntroductiontoRegexesinPerl5 Regexcharacterclasses Regex:specialcharacterclasses Perl5RegexQuantifiers trim-removingleadingandtrailingwhitespaceswithPerl Perl5RegexCheatsheet Shellrelatedfunctionality Whatare-e,-z,-s,-M,-A,-C,-r,-w,-x,-o,-f,-d,-linPerl? CurrentworkingdirectoryinPerl(cwd,pwd) RunningexternalprogramsfromPerlwithsystem qxorbackticks-runningexternalcommandandcapturingtheoutput Howtoremove,copyorrenameafilewithPerl Readingthecontentofadirectory Traversingthefilesystem-usingaqueue CPAN DownloadandinstallPerl InstallingaPerlModulefromCPANonWindows,LinuxandMacOSX Howtochange@INCtofindPerlmodulesinnon-standardlocations Howtoaddarelativedirectoryto@INC ExamplesforusingPerl HowtoreplaceastringinafilewithPerl HowtoreadanExcelfileinPerl HowtocreateanExcelfilewithPerl? SendingHTMLe-mailusingEmail::Stuffer Perl/CGIscriptwithApache2 JSONinPerl SimpleDatabaseaccessusingPerlDBIandSQL ReadingfromLDAPinPerlusingNet::LDAP Commonwarningsanderrormessages Globalsymbolrequiresexplicitpackagename VariabledeclarationinPerl Useofuninitializedvalue BarewordsinPerl Name"main::x"usedonlyonce:possibletypoat... Unknownwarningscategory Can'tusestring(...)asanHASHrefwhile"strictrefs"inuseat... SymbolicreferencesinPerl Can'tlocate...in@INC Scalarfoundwhereoperatorexpected "my"variablemasksearlierdeclarationinsamescope Can'tcallmethod...onunblessedreference Argument...isn'tnumericinnumeric... Can'tlocateobjectmethod"..."viapackage"1"(perhapsyouforgottoload"1"?) Uselessuseofhashelementinvoidcontext Uselessuseofprivatevariableinvoidcontext readline()onclosedfilehandleinPerl Possibleprecedenceissuewithcontrolflowoperator Scalarvalue...betterwrittenas... substroutsideofstringat... Haveexceededthemaximumnumberofattempts(1000)toopentempfile/dir Useofimplicitsplitto@_isdeprecated... Other MultidimensionalarraysinPerl MultidimensionalhashesinPerl MinimalrequirementtobuildasaneCPANpackage Statementmodifiers:reversedifstatements Whatisautovivification? FormattedprintinginPerlusingprintfandsprintf Processingcommandlinearguments-@ARGVinPerl @ARGV $ARGV[] $0 shift argc Prev Next IfyouwroteaPerlscript,forexampleprogramming.pl, youruserscanrunthescriptonthecommandlineusingperlprogramming.pl. Theycanalsopassanycommandlineargumentslikethisperlprogramming.pl-a--machineremote/etc. Noonewillstoptheusersfromdoingthat,andthescriptwilldisregardthesevalues. Thequestionthenhowcanyou,theauthorofthescript,knowwhichvalueswerepassed,ifany? Commandline Perlautomaticallyprovidesanarraycalled@ARGV,thatholdsallthevaluesfromthecommandline. Youdon'thavetodeclarethevariable,evenifyouusestrict. Thisvariablealwaysexistsandthevaluesfromthecommandlineareautomaticallyplacedinthisvariable. Iftherearenoparameters,thearraywillbeempty.Ifthereisoneparameteronthecommandline,thatvaluewill [email protected]@ARGVwillhavethefollowingelements: -a,--machine,remote,/etc Let'sseethisinaction: Savethiscodeasprogramming.pl: usestrict; usewarnings; useData::Dumperqw(Dumper); printDumper\@ARGV; Runitlikethis:perlprogramming.pl-a--machineremote/etcandthisistheoutput: $VAR1=[ '-a', '--machine', 'remote', '/etc' ]; AsyoucanseeweusedtheDumperfunctionofData::Dumpertoprint outthecontentof@ARGV Ifyouarecomingfromanotherprogramminglanguage,youmightbewondering: whereisthenameofthePerlprogram? Thenameofthescriptisin$0 Thenameoftheprogrambeingexecuted,intheabovecaseprogramming.pl,isalwaysinthe$0 variableofPerl.(Pleasenote,$1,$2,etc.areunrelated!) Cprogrammer IncaseyouknowtheCprogramminglanguage,thisissimilartoargv,exceptthatthe @ARGVofPerldoesnotcontainthenameoftheprogram. Itcanbefoundinthe$0variable.Alsoavariablesuchasargcisnotnecessary, asyoucaneasilygetthenumberofelementsinthe@ARGVarray usingthescalarfunctionorbyputtingthearrayin scalarcontext. Unix/LinuxShellprogramming IncaseyouarrivefromtheworldofUnix/LinuxShellprogrammingyouwillrecognize$0 isbeingthenameofthescripttheretoo.Inshellhowever$1,$2,etc. holdtherestofthecommandlineparameters.Thesevariablesareusedby theregularexpressionsofPerl.Thecommandlineargumentsarein@ARGV.Similarto$* intheUnix/Linuxshell. Howtoextractthecommandlineargumentsfrom@ARGV @ARGVisjustaregulararrayinPerl. Theonlydifferencefromarraysthatyoucreate,isthatitdoesnot needtobedeclaredanditispopulatedbyPerlwhenyourscriptstarts. Asidefromtheseissue,youcanhandleitasaregulararray. Youcangoovertheelementsusingforeach,oraccessthemonebyoneusinganindex:$ARGV[0]. Youcanalsouseshift,unshift,poporpushonthisarray. Indeed,notonlycanyoufetchthecontentof@ARGV,youcanalsochangeit. Ifyouexpectasinglevalueonthecommandlineyoucancheckwhatwasit,orifitwasprovidedatall bylookingat$ARGV[0].Ifyouexpecttwovariablesyouwillalsocheck$ARGV[1]. Forexample,let'screateaphonebook.Ifyouprovideonename,theapplicationwillprintthecorrespondingphone number.Ifyougiveanameandanumbertheprogramwillsavethatpairinthe"database". (Wewon'tactuallyhandlethe"database"partofthecode,wejustpretendwehavesomething.) Weknowthattheparameterswillarrivein$ARGV[0]andmaybealsoin$ARGV[1],but thosehavenomeaningbesidesbeingthefirstandsecondelementofanarray. Usuallyitisbettertouseyourownnamedvariablesinyourcodeinsteadof$ARGV[0]andsimilar. Sothefirstthingwe'llwantistocopythevaluestovariableswithrepresentativenames: Thiscanwork: my$name=$ARGV[0]; my$number=$ARGV[1]; Butthisismuchnicer: my($name,$number)=@ARGV; Let'snowseethefullexample(well,exceptofthedatabasepart). Savethefollowingcodeinprogramming.pl. usestrict; usewarnings; my($name,$number)=@ARGV; if(notdefined$name){ die"Needname\n"; } if(defined$number){ print"Save'$name'and'$number'\n"; #savename/numberindatabase exit; } print"Fetch'$name'\n"; #lookupthenameinthedatabaseandprintitout Aftercopyingthevaluesfrom@ARGV,wecheckifthenamewasprovided. Ifnot,wecalldiethatwillprintanerrormessageandexitthescript. Iftherewasaname,thenwecheckforthenumber.Iftherewasanumberwesave itinthedatabase(whichisnotimplementedabove)andexitthescript. Iftherewasnonumberthenwetrytofetchitfromthedatabase.(Again,notimplementedhere.) Let'sseehowitworks:(The$signonlymarkstheprompt,wedon'ttypethat.) $perlprogramming.plFoo123 Save'Foo'and'123' $perlprogramming.plBar456 Save'Bar'and'456' $perlprogramming.plJohnDoe789 Save'John'and'Doe' ThefirsttwocallswereOK,butthelastonedoesnotlookgood. Wewantedtosavethephonenumberof"JohnDoe"tobe789,butinsteadofthat ourscriptsavedthephonenumberof"John"asifitwas"Doe". Thereasonissimple,andithasnothingtodowithPerl.Thiswouldworkthesameinanyotherlanguage. Theshellorcommandline,whereyourunthescripttakesthelineapartandpassesthevaluestoperlwhichthen [email protected]/LinuxshellandtheWindowsCommandLinewillsplitthecommandline ateveryspace.Sowhenwetypedperlprogramming.plJohnDoe789,theshellactuallypassed3parametersto ourscript.Inordertomakeitworkcorrectlytheuserhastoputthevaluesthathaveembeddedspacesinsidequotes: $perla.pl"JohnDoe"789 Save'JohnDoe'and'789' You,astheprogrammercannotdomuchaboutthis. Checkingthearguments Maybeyoucouldcheckifthenumberofelementsdoesnotexceedthenumberyouexpected. Itwouldstoptheuserfrommakingtheabovemistake,butwhatiftheuserwants tofetchthephonenumberofJohnDoeandforgetsthequotes: perla.plJohnDoe Save'John'and'Doe' Inthiscasetherewere2parameterswhichisthecorrectnumberofarguments. Heretoo,youcouldmakeaslightimprovementandcheckifthecontentofthe$numbervariable isinaformatyouacceptasphonenumber.Thatwouldreducethepossibilityformistakesinthiscase. Thatstillwouldnotbeperfectandcertainlynotanuniversalsolution: Inotherapplicationstheremightbeseveralparameterswiththesameconstraints. Unfortunatelythereisnotalotwecandowhenparsing@ARGV"manually". InanotherarticleI'llwriteaboutGetopt::Longandsimilarlibraries thatmakelifeabiteasier,butlet'sseeanothersimplecasenow. shiftasingleparameter Acommoncaseiswhenyouexpecttheusertoprovideasinglefilenameonthecommandline. Inthatcaseyoucouldwritethefollowingcode: my$filename=shiftordie"Usage:$0FILENAME\n"; Let'sbreakthatlineintotwopartsforeasierexplanation: my$filename=shift Normallyshiftwouldgetanarrayasitsparameter, butinthiscaseweuseditwithoutaparameter.Insuchcasesshiftdefaultstowork [email protected]@ARGVtothe $filenamevariable.(Atleastwhenthecodeisnotinasubroutine.) Thenwebasicallyhavethefollowingcode: $filenameordie"Usage:$0FILENAME\n" Thisisabooleanexpression. Ifthe$filenamecontainsthenameofafile thenitwillbeconsideredTrueandthescriptwillgo onrunningwithoutexecutingtheordie...part. Ontheotherhand,ifthe@ARGVwasempty,$filenamewasassignedundef, anditwillcountasFalse andPerlwillexecutetheright-hand-sideoftheorstatement, printingamessagetothescreenandexitingthescript. Soeffectively,thispieceofcodewouldcheckifavaluewasprovidedonthecommandline.Thevalue iscopiedto$filename.Iftherewasnovalue,thescriptwoulddie. Minorbug Thereisoneminorbugintheabovecode.Iftheusersupplies0asthenameofthefile.Itwillstill beseenasFalseandthescriptwillrefusetohandlesuchafile.Thequestionthough:Doesitmatter? Canwelivewiththefactthatourscriptmightnothandleafilecalled0...? Complexcases Therearealotofothercasesthataremuchmorecomplexthantheaboveoneortwoparametercases. Forthosecasesyou'dprobablywanttouseatoolsuchasGetopt::Longthatwillbeabletoanalyze thecontentof@ARGVbasedonsomedeclarationofwhatkindofparametersyou'dwanttoaccept. Prev Next Writtenby GaborSzabo Publishedon2013-07-07 Comments Inthecomments,pleasewrapyourcodesnippetswithin

tagsandusespacesforindentation.




commentspoweredbyDisqus










Ifyouhaveanycommentsorquestions,feelfreetopostthemonthesourceofthispageinGitHub.SourceonGitHub.
Commentonthispost
















Author:GaborSzabo

GaborwhorunsthePerlMavensitehelpscompaniessetuptestautomation,CI/CD
ContinuousIntegrationandContinuousDeploymentandotherDevOpsrelated
systems.

GaborcanhelprefactoryouroldPerlcode-base.

HerunsthePerlWeeklynewsletter.

ContactGaborifyou'dliketohirehisservice.

BuyhiseBooksorifyoujustwouldliketosupporthim,doitviaPatreon.
























English




Español




Türkçe




עברית




한국어




aboutthetranslations



















BooleanvaluesinPerl

ManipulatingPerlarrays:shift,unshift,push,pop

PerlArrays

ScalarandListcontextinPerl,thesizeofanarray

































請為這篇文章評分?