Parsing Command Line Options - The Perl Journal, Summer ...

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

Parsing Command Line Options. Johan Vromans. PACKAGES USED. Package, Version. Perl, 5. Getopt::Std and. Getopt ... PREVIOUS  TABLEOFCONTENTS  NEXT  ParsingCommandLineOptions JohanVromans PACKAGESUSED Package Version Perl 5 Getopt::StdandGetopt::Long bothbundledwithPerl5;recentversionsofGetopt::LongareonCPAN Controllingacomputerbytypingcommandsintoashellisstillthepreferredwayofworkingformostprogrammers.Despitethecapabilitiesofmodernwindowsystems,workingfromashellismuchfasterandlesscomplicatedthansequencesofmousemovementsandbuttonclicks-onceyouknowthe namesofthecommandsandhowtheywork. Theexpressivenessofacommand-lineprogramdependson whatoptionsitsupports,andhowthey'reparsed-converted intoaformthatyourprogramcanunderstand.Whenyouexecute ls-l/tmponUnix,ordir/wc:\windowsonMS-DOS,oryour_program-height=80,the-l,/w,and-height=80areoptions.Sometimestheshellhandlestheparsing;that'swhathappenswiththe/winDOS.Moreoften,theprogramnamedbythecommand(lsandyour_program)musthandletheparsingitself.Inthisarticle,I'llshowyouhowyourPerlprogramscanparsetheirownoptions. OPTIONPARSINGCONVENTIONS Undermoderncommandshells,includingthoseonUnixand Windows,optionscanbeeitherlettersorwords.Programsthat acceptsinglelettersmightbeinvokedlikeprogram-a-b-c.Or,theymightlookbeinvokedasprogram-abc,meaningthesamething.Iftheoptionstakevalues,youcanbundlethemtogether:-aw80L24xisequivalentto-a-w80-L24-x.Withoptionwords,yousacrificebrevityforclarity:program--all--width=80--length24--extend. Ineithercase,optionsprecedeotherprogramarguments(the /tmpinls-l/tmp)andtheparsingstopsassoonasanon-optionargumentisencountered.Adoubledashbyitselfimmediatelyterminatesoptionparsing. Theseconventionsaren'tuniversal.Someprogramsaccept optionwordswithasingledash(e.g.-hforheight);someletyoumixoptionlettersandoptionwords;someletyoumix optionsandregularprogramarguments.Optionscanbemandatory oroptional,case-sensitiveorcase-insensitive,andcan expectanargumentafterward-ornot. ParsingoptionsinPerlisn'tveryhard,butafterwritingeight subroutinesforeightprograms,youmightwonderwhether there'sabetterway.Thereis.Infact,thereareseveralways. THESIMPLESTWAY Perldirectlysupportsthesingle-characterstyleofoptionswith the-sswitch.IfyoustartPerlas perl-sscript.pl-foo-barmyfile.dat Perlwillremoveanythingthatlookslikeanoption(-fooand-bar)fromthecommandlineandsetthevariables($fooand$bar)totrue.Notethattheoptionsarewordsprecededwithasingledash.WhenPerlencountersanargumentwithoutthedash,itstopslookingforoptions. THEEASYWAY Perlcomeswithtwomodulesthathandlecommandline options:Getopt::StdandGetopt::Long. Getopt::Stdprovidestwosubroutines,getopt()and getopts().Eachexpectsasingledashbeforeoptionlettersandstopsprocessingoptionswhenthefirstnon-optionisdetected. getopt()takesoneargument,astringcontainingalltheoptionlettersthatexpectvalues.Forexample,getopt('lw')letsyourprogrambeinvokedasprogram-l24-w80(orprogram-l24-w80),anditwillset$opt_lto24and$opt_wto80.Otheroptionlettersarealsoaccepted;forexample,program-l24-ab willalsosetboth$opt_aand$opt_bto1. Whenyoudon'twantglobalvariablesdefinedinthisway,you canpassahashreferencetogetopt().Thekeysaretheoptionletters,andthevalueswillbefilledwiththevalues(or1iftheoptiondoesn'ttakeavalue). getopts()allowsalittlebitmorecontrol.Itsargumentisastringcontainingtheoptionlettersofallrecognizedoptions. Optionsthattakevaluesarefollowedbycolons.Forexample, getopts('abl:w:')makesyourprogramaccept-aand-bwithoutavalue,and-land-wwithavalue.Anyotherargumentsbeginningwithadashresultinanerror.Aswithgetopt(),ahashreferencecanbepassedasanoptionalsecondargument. THEADVANCEDWAY Getopt::LongprovidestheGetOptions()function,whichgivesyouultimatecontrolovercommandlineoptions.Itprovides supportfor: single-letteroptions,withbundling(-abc); optionwords,usingasingledash,doubledash,orplussign(astandardbrieflyadoptedbyGNU) amixoftheabove,inwhichcasethelongoptionsmuststartwithadoubledash. Otherfeatures: optionvaluescanbedesignatedmandatoryoroptional optionvaluescanbestringsornumbers fullcontroloverwheretheoptionvaluewillbedelivered fullcheckingofoptionsandvalues Thisarticledescribesversion2.17oftheGetopt::Longmodule. OptionWords.Initsstandardconfiguration,GetOptions() handlesoptionwords,ignoringcase.Optionsmaybeabbrevi-ated, aslongastheabbreviationsareunambiguous.Optionsand othercommandlineargumentscanbemixed;optionswillbe processedfirst,andtheotherargumentswillremainin@ARGV. ThiscalltoGetOptions()allowsasingleoption,-foo. GetOptions('foo'=>\$doit); Whentheuserprovides-fooonthecommandline,$doitissetto1.Inthiscall,-fooiscalledtheoptioncontrolstring,and\$doitiscalledtheoptiondestination.Multiplepairsofcontrolstringsanddestinationscanbeprovided.GetOptions()willreturntrueifprocessingwassuccessful,andfalseotherwise,displayinganerrormessagewithwarn(). Theoptionwordmayhavealiases,alternativeoptionwordsthatrefertothesameoption: GetOptions('foo|bar|quux'=>\$doit); Ifyouwanttospecifythatanoptiontakesastring,append=stotheoptioncontrolstring: GetOptions('foo=s'=>\$thevalue); Whenyouuseacoloninsteadofanequalsign,theoptiontakes avalueonlywhenoneispresent: GetOptions('foo:s'=>\$thevalue,'bar'=>\$doit); Callingthisprogramwitharguments-foobarblechplaces thestring'bar'in$thevalue,butwhencalledwith-foo-barblech,somethingdifferenthappens:$thevalueissettoanemptystring,and$barissetto1. Theseoptionscanalsotakenumericvalues;youcanuse=ior:iforintegervalues,and=for:fforfloatingpointvalues. UsingandBundlingSingle-LetterOptions.Usingsingle-letter optionsistrivial;bundlingthemisalittletrickier. Getopt::LonghasaConfigure()subroutinethatyoucanusetofine-tuneyouroptionparsing.Forbundlingsingle-letter options,youwoulduseGetopt::Long::Configure('bundling').NowGetOptions()willhappilyacceptbundledsingle-letteroptions: Getopt::Long::Configure('bundling'); GetOptions('a'=>\$all, 'l=i'=>\$length, 'w=i'=>\$width); Thisallowsoptionsoftheform-a-l24-w80aswellasbundled forms:-al24w80.Youcanmixthesewithoptionwords: GetOptions('a|all'=>\$all, 'l|length=i'=>\$length, 'w|width=i'=>\$width); However,theoptionwordsrequireadoubledash:--width24 isacceptable,but-width24isnot.(Thatcausestheleadingwtobeinterpretedas-w,andresultsinanerrorbecauseidthisn'tavalidintegervalue. Getopt::Long::Configure('bundling_override')allowsoption wordswithasingledash,wherethewordstakeprecedenceover bundledsingle-letteroptions.Forexample: Getopt::Long::Configure('bundling_override'); GetOptions('a'=>\$a,'v'=>\$v, 'x'=>\$x,'vax'=>\$vax); Thistreats-axvas-a-x-v,buttreats-vaxasasingleoptionword. Advanceddestinations.Youdon'tneedtospecifytheoption destination.Ifyoudon't,GetOptions()definesvariables $opt_xxx(wherexxxisthenameoftheoption),justlikegetopt()andgetopts().Similarly,GetOptions()alsoacceptsareferencetoahash(asitsfirstargument)andplacestheoptionvaluesinit. Ifyoudospecifytheoptiondestination,itneedn'tbeascalar.Ifyouspecifyanarrayreference,optionvaluesarepushedinto thisarray: GetOptions('foo=i'=>\@values); Callingthisprogramwitharguments-foo1-foo2-foo3 sets@valuesto(1,2,3). Theoptiondestinationcanalsobeahashreference: my%values; GetOptions('define=s'=>\%values); Ifyoucallthisprogramasprogram-defineEOF=-1-define bool=int,the%valueshashwillhavethekeysEOFandbool,setto-1and'int'respectively. Finally,thedestinationcanbeareferencetoasubroutine.This subroutinewillbecalledwhentheoptionishandled.Itexpects twoarguments:thenameoftheoptionandthevalue. Thespecialoptioncontrolstring'<>'canbeusedinthiscasetohaveasubroutineprocessargumentsthataren'toptions.Thissubroutineisthencalledwiththenameofthenon-optionargument.Consider: GetOptions('x=i'=>\$x,'<>'=>\&doit); Whenyouexecutethisprogramwith-x1foo-x2barthis invokesdoit()withargument'foo'(and$xequalto1,andthencallsdoit()withargument'bar'(and$xequalto2). OtherConfigurations.GetOptions()supportsseveralotherconfigurationcharacteristics.Foracompletelist,seethe Getopt::Longdocumentation. Getopt::Long::Configure('no_ignore_case')matchesoption wordswithoutregardtocase. Getopt::Long::Configure('no_auto_abbrev')preventsabbreviationsforoptionwords. Getopt::Long::Configure('require_order')stopsdetecting optionsafterthefirstnon-optioncommandlineargument. Helpmessages.PeopleoftenaskmewhyGetOptions() doesn'tprovidefacilitiesforhelpmessages.Therearetworeasons.Thefirstreasonisthatwhilecommandlineoptionsadhere toconventions,helpmessagesdon't.Anystyleofmessage wouldnecessarilypleasesomepeopleandannoyothers,and wouldmakecallstoGetOptions()muchlengthierandmore confusing. ThesecondreasonisthatPerlallowsaprogramtocontain itsowndocumentationinPOD(PlainOldDocumentation) format,andtherearealreadymodulesthatextractthis informationtosupplyhelpmessages.Thefollowingsub-routine usesPod::Usageforthispurpose(anddemon-strates howPod::Usagecanbeloadedondemand): suboptions(){ my$help=0;#handledlocally my$ident=0;#handledlocally my$man=0;#handledlocally #Processoptions. if(@ARGV>0){ GetOptions('verbose'=>\$verbose, 'trace'=>\$trace, 'help|?'=>\$help, 'manual'=>\$man, 'debug'=>\$debug) orpod2usage(2); } if($manor$help){ #LoadPod::Usageonlyifneeded. require"Pod/Usage.pm"; importPod::Usage; pod2usage(1)if$help; pod2usage(VERBOSE=>2)if$man; } } Pod::Usageisavailableathttp://www.perl.com/CPAN/modules/authors/Brad_Appleton.ThelatestversionofGetopt::Long(2.17asofthiswriting)canbefoundin authors/Johan_Vromans.Thiskitalsocontainsascript templatethatusesbothGetopt::LongandPod::Usage. OTHEROPTIONHANDLINGMODULES AfewotheroptionhandlingmodulescanbefoundontheCPAN.Thefollowingmodulescanbedownloadedfromhttp://www.perl.com/CPAN/modules/by-category/12_Option_Argument_Parameter_Processing. Getopt::Mixedprovideshandlingoptionwordsandoptionletters.Itwasdevelopedacoupleofyearsago,whenGetopt::Std onlyhandledoptionlettersandGetopt::Longonlyhandled optionwords.It'sobsoletenow. Getopt::Regexisanoptionhandlerthatusesregularexpressionstoidentifytheoptions,andclosurestodelivertheoptionvalues. Getopt::EvaPusesatable-drivenoptionhandlerthatprovides helpmessagesinadditiontomostGetopt::Longfeatures. Getopt::Tabularisanothertable-drivenoptionhandlerlooselyinspiredbyTcl/Tk.Powerful,butverycomplextosetup. __END__ JohanVromans([email protected])hasbeenengagedin softwareengineeringsince1975.HehasbeenaPerlusersince version2andparticipatedactivelyinitsdevelopment.Besides beingtheauthorofGetopt::Long,hewrotethePerl5DesktopReferenceandco-authoredTheWebmaster'sHandbook. PREVIOUS  TABLEOFCONTENTS  NEXT 



請為這篇文章評分?