Getopt::Long - Extended processing of command line options

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

To use Getopt::Long from a Perl program, you must include the following line in ... If an argument callback routine is specified, @ARGV will always be empty ... 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 Getopt::Long (source, CPAN) version2.52 CONTENTS NAME SYNOPSIS DESCRIPTION CommandLineOptions,anIntroduction GettingStartedwithGetopt::Long Simpleoptions Alittlebitlesssimpleoptions Mixingcommandlineoptionwithotherarguments Optionswithvalues Optionswithmultiplevalues Optionswithhashvalues User-definedsubroutinestohandleoptions Optionswithmultiplenames Caseandabbreviations SummaryofOptionSpecifications AdvancedPossibilities Objectorientedinterface Callbackobject ThreadSafety Documentationandhelptexts Parsingoptionsfromanarbitraryarray Parsingoptionsfromanarbitrarystring Storingoptionsvaluesinahash Bundling Thelonesomedash Argumentcallback ConfiguringGetopt::Long ExportableMethods ReturnvaluesandErrors Legacy Defaultdestinations Alternativeoptionstarters Configurationvariables TipsandTechniques Pushingmultiplevaluesinahashoption Troubleshooting GetOptionsdoesnotreturnafalseresultwhenanoptionisnotsupplied GetOptionsdoesnotsplitthecommandlinecorrectly Undefinedsubroutine&main::GetOptionscalled HowdoIputa"-?"optionintoaGetopt::Long? AUTHOR COPYRIGHTANDDISCLAIMER #NAME Getopt::Long-Extendedprocessingofcommandlineoptions #SYNOPSIS useGetopt::Long; my$data="file.dat"; my$length=24; my$verbose; GetOptions("length=i"=>\$length,#numeric "file=s"=>\$data,#string "verbose"=>\$verbose)#flag ordie("Errorincommandlinearguments\n"); #DESCRIPTION TheGetopt::LongmoduleimplementsanextendedgetoptfunctioncalledGetOptions().Itparsesthecommandlinefrom@ARGV,recognizingandremovingspecifiedoptionsandtheirpossiblevalues. ThisfunctionadherestothePOSIXsyntaxforcommandlineoptions,withGNUextensions.Ingeneral,thismeansthatoptionshavelongnamesinsteadofsingleletters,andareintroducedwithadoubledash"--".Supportforbundlingofcommandlineoptions,aswasthecasewiththemoretraditionalsingle-letterapproach,isprovidedbutnotenabledbydefault. #CommandLineOptions,anIntroduction Commandlineoperatedprogramstraditionallytaketheirargumentsfromthecommandline,forexamplefilenamesorotherinformationthattheprogramneedstoknow.Besidesarguments,theseprogramsoftentakecommandlineoptionsaswell.Optionsarenotnecessaryfortheprogramtowork,hencethename'option',butareusedtomodifyitsdefaultbehaviour.Forexample,aprogramcoulddoitsjobquietly,butwithasuitableoptionitcouldprovideverboseinformationaboutwhatitdid. Commandlineoptionscomeinseveralflavours.Historically,theyareprecededbyasingledash-,andconsistofasingleletter. -l-a-c Usually,thesesingle-characteroptionscanbebundled: -lac Optionscanhavevalues,thevalueisplacedaftertheoptioncharacter.Sometimeswithwhitespaceinbetween,sometimesnot: -s24-s24 Duetotheverycrypticnatureoftheseoptions,anotherstylewasdevelopedthatusedlongnames.Soinsteadofacryptic-lonecouldusethemoredescriptive--long.Todistinguishbetweenabundleofsingle-characteroptionsandalongone,twodashesareusedtoprecedetheoptionname.Earlyimplementationsoflongoptionsusedaplus+instead.Also,optionvaluescouldbespecifiedeitherlike --size=24 or --size24 The+formisnowobsoleteandstronglydeprecated. #GettingStartedwithGetopt::Long Getopt::LongisthePerl5successorofnewgetopt.pl.ThiswasthefirstPerlmodulethatprovidedsupportforhandlingthenewstyleofcommandlineoptions,inparticularlongoptionnames,hencethePerl5nameGetopt::Long.Thismodulealsosupportssingle-characteroptionsandbundling. TouseGetopt::LongfromaPerlprogram,youmustincludethefollowinglineinyourPerlprogram: useGetopt::Long; ThiswillloadthecoreoftheGetopt::Longmoduleandprepareyourprogramforusingit.MostoftheactualGetopt::Longcodeisnotloadeduntilyoureallycalloneofitsfunctions. Inthedefaultconfiguration,optionsnamesmaybeabbreviatedtouniqueness,casedoesnotmatter,andasingledashissufficient,evenforlongoptionnames.Also,optionsmaybeplacedbetweennon-optionarguments.See"ConfiguringGetopt::Long"formoredetailsonhowtoconfigureGetopt::Long. #Simpleoptions Themostsimpleoptionsaretheonesthattakenovalues.Theirmerepresenceonthecommandlineenablestheoption.Popularexamplesare: --all--verbose--quiet--debug Handlingsimpleoptionsisstraightforward: my$verbose=''; #optionvariablewithdefaultvalue(false) my$all=''; #optionvariablewithdefaultvalue(false) GetOptions('verbose'=>\$verbose,'all'=>\$all); ThecalltoGetOptions()parsesthecommandlineargumentsthatarepresentin@ARGVandsetstheoptionvariabletothevalue1iftheoptiondidoccuronthecommandline.Otherwise,theoptionvariableisnottouched.Settingtheoptionvaluetotrueisoftencalledenablingtheoption. TheoptionnameasspecifiedtotheGetOptions()functioniscalledtheoptionspecification.Laterwe'llseethatthisspecificationcancontainmorethanjusttheoptionname.Thereferencetothevariableiscalledtheoptiondestination. GetOptions()willreturnatruevalueifthecommandlinecouldbeprocessedsuccessfully.Otherwise,itwillwriteerrormessagesusingdie()andwarn(),andreturnafalseresult. #Alittlebitlesssimpleoptions Getopt::Longsupportstwousefulvariantsofsimpleoptions:negatableoptionsandincrementaloptions. Anegatableoptionisspecifiedwithanexclamationmark!aftertheoptionname: my$verbose=''; #optionvariablewithdefaultvalue(false) GetOptions('verbose!'=>\$verbose); Now,using--verboseonthecommandlinewillenable$verbose,asexpected.Butitisalsoallowedtouse--noverbose,whichwilldisable$verbosebysettingitsvalueto0.Usingasuitabledefaultvalue,theprogramcanfindoutwhether$verboseisfalsebydefault,ordisabledbyusing--noverbose. Anincrementaloptionisspecifiedwithaplus+aftertheoptionname: my$verbose=''; #optionvariablewithdefaultvalue(false) GetOptions('verbose+'=>\$verbose); Using--verboseonthecommandlinewillincrementthevalueof$verbose.Thiswaytheprogramcankeeptrackofhowmanytimestheoptionoccurredonthecommandline.Forexample,eachoccurrenceof--verbosecouldincreasetheverbosityleveloftheprogram. #Mixingcommandlineoptionwithotherarguments Usuallyprogramstakecommandlineoptionsaswellasotherarguments,forexample,filenames.Itisgoodpracticetoalwaysspecifytheoptionsfirst,andtheotherargumentslast.Getopt::Longwill,however,allowtheoptionsandargumentstobemixedand'filterout'alltheoptionsbeforepassingtherestoftheargumentstotheprogram.TostopGetopt::Longfromprocessingfurtherarguments,insertadoubledash--onthecommandline: --size24----all Inthisexample,--allwillnotbetreatedasanoption,butpassedtotheprogramunharmed,in@ARGV. #Optionswithvalues Foroptionsthattakevaluesitmustbespecifiedwhethertheoptionvalueisrequiredornot,andwhatkindofvaluetheoptionexpects. Threekindsofvaluesaresupported:integernumbers,floatingpointnumbers,andstrings. Iftheoptionvalueisrequired,Getopt::Longwilltakethecommandlineargumentthatfollowstheoptionandassignthistotheoptionvariable.If,however,theoptionvalueisspecifiedasoptional,thiswillonlybedoneifthatvaluedoesnotlooklikeavalidcommandlineoptionitself. my$tag=''; #optionvariablewithdefaultvalue GetOptions('tag=s'=>\$tag); Intheoptionspecification,theoptionnameisfollowedbyanequalssign=andtheletters.Theequalssignindicatesthatthisoptionrequiresavalue.Thelettersindicatesthatthisvalueisanarbitrarystring.Otherpossiblevaluetypesareiforintegervalues,andfforfloatingpointvalues.Usingacolon:insteadoftheequalssignindicatesthattheoptionvalueisoptional.Inthiscase,ifnosuitablevalueissupplied,stringvaluedoptionsgetanemptystring''assigned,whilenumericoptionsaresetto0. #Optionswithmultiplevalues Optionssometimestakeseveralvalues.Forexample,aprogramcouldusemultipledirectoriestosearchforlibraryfiles: --librarylib/stdlib--librarylib/extlib Toaccomplishthisbehaviour,simplyspecifyanarrayreferenceasthedestinationfortheoption: GetOptions("library=s"=>\@libfiles); Alternatively,youcanspecifythattheoptioncanhavemultiplevaluesbyaddinga"@",andpassareferencetoascalarasthedestination: GetOptions("library=s@"=>\$libfiles); Usedwiththeexampleabove,@libfilesc.q.@$libfileswouldcontaintwostringsuponcompletion:"lib/stdlib"and"lib/extlib",inthatorder.Itisalsopossibletospecifythatonlyintegerorfloatingpointnumbersareacceptablevalues. Oftenitisusefultoallowcomma-separatedlistsofvaluesaswellasmultipleoccurrencesoftheoptions.ThisiseasyusingPerl'ssplit()andjoin()operators: GetOptions("library=s"=>\@libfiles); @libfiles=split(/,/,join(',',@libfiles)); Ofcourse,itisimportanttochoosetherightseparatorstringforeachpurpose. Warning:Whatfollowsisanexperimentalfeature. Optionscantakemultiplevaluesatonce,forexample --coordinates52.216.4--rgbcolor255255149 Thiscanbeaccomplishedbyaddingarepeatspecifiertotheoptionspecification.Repeatspecifiersareverysimilartothe{...}repeatspecifiersthatcanbeusedwithregularexpressionpatterns.Forexample,theabovecommandlinewouldbehandledasfollows: GetOptions('coordinates=f{2}'=>\@coor,'rgbcolor=i{3}'=>\@color); Thedestinationfortheoptionmustbeanarrayorarrayreference. Itisalsopossibletospecifytheminimalandmaximalnumberofargumentsanoptiontakes.foo=s{2,4}indicatesanoptionthattakesatleasttwoandatmost4arguments.foo=s{1,}indicatesoneormorevalues;foo:s{,}indicateszeroormoreoptionvalues. #Optionswithhashvalues Iftheoptiondestinationisareferencetoahash,theoptionwilltake,asvalue,stringsoftheformkey=value.Thevaluewillbestoredwiththespecifiedkeyinthehash. GetOptions("define=s"=>\%defines); Alternativelyyoucanuse: GetOptions("define=s%"=>\$defines); Whenusedwithcommandlineoptions: --defineos=linux--definevendor=redhat thehash%defines(or%$defines)willcontaintwokeys,"os"withvalue"linux"and"vendor"withvalue"redhat".Itisalsopossibletospecifythatonlyintegerorfloatingpointnumbersareacceptablevalues.Thekeysarealwaystakentobestrings. #User-definedsubroutinestohandleoptions Ultimatecontroloverwhatshouldbedonewhen(actually:eachtime)anoptionisencounteredonthecommandlinecanbeachievedbydesignatingareferencetoasubroutine(orananonymoussubroutine)astheoptiondestination.WhenGetOptions()encounterstheoption,itwillcallthesubroutinewithtwoorthreearguments.Thefirstargumentisthenameoftheoption.(Actually,itisanobjectthatstringifiestothenameoftheoption.)Forascalarorarraydestination,thesecondargumentisthevaluetobestored.Forahashdestination,thesecondargumentisthekeytothehash,andthethirdargumentthevaluetobestored.Itisuptothesubroutinetostorethevalue,ordowhateveritthinksisappropriate. Atrivialapplicationofthismechanismistoimplementoptionsthatarerelatedtoeachother.Forexample: my$verbose=''; #optionvariablewithdefaultvalue(false) GetOptions('verbose'=>\$verbose, 'quiet'=>sub{$verbose=0}); Here--verboseand--quietcontrolthesamevariable$verbose,butwithoppositevalues. Ifthesubroutineneedstosignalanerror,itshouldcalldie()withthedesirederrormessageasitsargument.GetOptions()willcatchthedie(),issuetheerrormessage,andrecordthatanerrorresultmustbereturneduponcompletion. Ifthetextoftheerrormessagestartswithanexclamationmark!itisinterpretedspeciallybyGetOptions().Thereiscurrentlyonespecialcommandimplemented:die("!FINISH")willcauseGetOptions()tostopprocessingoptions,asifitencounteredadoubledash--. Hereisanexampleofhowtoaccesstheoptionnameandvaluefromwithinasubroutine: GetOptions('opt=i'=>\&handler); subhandler{ my($opt_name,$opt_value)=@_; print("Optionnameis$opt_nameandvalueis$opt_value\n"); } #Optionswithmultiplenames Oftenitisuserfriendlytosupplyalternatemnemonicnamesforoptions.Forexample--heightcouldbeanalternatenamefor--length.Alternatenamescanbeincludedintheoptionspecification,separatedbyverticalbar|characters.Toimplementtheaboveexample: GetOptions('length|height=f'=>\$length); Thefirstnameiscalledtheprimaryname,theothernamesarecalledaliases.Whenusingahashtostoreoptions,thekeywillalwaysbetheprimaryname. Multiplealternatenamesarepossible. #Caseandabbreviations Withoutadditionalconfiguration,GetOptions()willignorethecaseofoptionnames,andallowtheoptionstobeabbreviatedtouniqueness. GetOptions('length|height=f'=>\$length,"head"=>\$head); Thiscallwillallow--land--Lforthelengthoption,butrequiresaleast--heaand--heifortheheadandheightoptions. #SummaryofOptionSpecifications Eachoptionspecifierconsistsoftwoparts:thenamespecificationandtheargumentspecification. Thenamespecificationcontainsthenameoftheoption,optionallyfollowedbyalistofalternativenamesseparatedbyverticalbarcharacters. length optionnameis"length" length|size|lnameis"length",aliasesare"size"and"l" Theargumentspecificationisoptional.Ifomitted,theoptionisconsideredboolean,avalueof1willbeassignedwhentheoptionisusedonthecommandline. Theargumentspecificationcanbe #! Theoptiondoesnottakeanargumentandmaybenegatedbyprefixingitwith"no"or"no-".E.g."foo!"willallow--foo(avalueof1willbeassigned)aswellas--nofooand--no-foo(avalueof0willbeassigned).Iftheoptionhasaliases,thisappliestothealiasesaswell. Usingnegationonasingleletteroptionwhenbundlingisineffectispointlessandwillresultinawarning. #+ Theoptiondoesnottakeanargumentandwillbeincrementedby1everytimeitappearsonthecommandline.E.g."more+",whenusedwith--more--more--more,willincrementthevaluethreetimes,resultinginavalueof3(provideditwas0orundefinedatfirst). The+specifierisignorediftheoptiondestinationisnotascalar. #=type[desttype][repeat] Theoptionrequiresanargumentofthegiventype.Supportedtypesare: #s String.Anarbitrarysequenceofcharacters.Itisvalidfortheargumenttostartwith-or--. #i Integer.Anoptionalleadingplusorminussign,followedbyasequenceofdigits. #o Extendedinteger,Perlstyle.Thiscanbeeitheranoptionalleadingplusorminussign,followedbyasequenceofdigits,oranoctalstring(azero,optionallyfollowedby'0','1',..'7'),orahexadecimalstring(0xfollowedby'0'..'9','a'..'f',caseinsensitive),orabinarystring(0bfollowedbyaseriesof'0'and'1'). #f Realnumber.Forexample3.14,-6.23E24andsoon. Thedesttypecanbe@or%tospecifythattheoptionislistorahashvalued.Thisisonlyneededwhenthedestinationfortheoptionvalueisnototherwisespecified.Itshouldbeomittedwhennotneeded. Therepeatspecifiesthenumberofvaluesthisoptiontakesperoccurrenceonthecommandline.Ithastheformat{[min][,[max]]}. mindenotestheminimalnumberofarguments.Itdefaultsto1foroptionswith=andto0foroptionswith:,seebelow.Notethatminoverrulesthe=/:semantics. maxdenotesthemaximumnumberofarguments.Itmustbeatleastmin.Ifmaxisomitted,butthecommaisnot,thereisnoupperboundtothenumberofargumentvaluestaken. #:type[desttype] Like=,butdesignatestheargumentasoptional.Ifomitted,anemptystringwillbeassignedtostringvaluesoptions,andthevaluezerotonumericoptions. Notethatifastringargumentstartswith-or--,itwillbeconsideredanoptiononitself. #:number[desttype] Like:i,butifthevalueisomitted,thenumberwillbeassigned. #:+[desttype] Like:i,butifthevalueisomitted,thecurrentvaluefortheoptionwillbeincremented. #AdvancedPossibilities #Objectorientedinterface Getopt::Longcanbeusedinanobjectorientedwayaswell: useGetopt::Long; $p=Getopt::Long::Parser->new; $p->configure(...configurationoptions...); if($p->getoptions(...optionsdescriptions...))... if($p->getoptionsfromarray(\@array,...optionsdescriptions...))... Configurationoptionscanbepassedtotheconstructor: $p=newGetopt::Long::Parser config=>[...configurationoptions...]; #Callbackobject Inversion2.37thefirstargumenttothecallbackfunctionwaschangedfromstringtoobject.Thiswasdonetomakeroomforextensionsandmoredetailedcontrol.Theobjectstringifiestotheoptionnamesothischangeshouldnotintroducecompatibilityproblems. Thecallbackobjecthasthefollowingmethods: #name Thenameoftheoption,unabbreviated.Foranoptionwithmultiplenamesitreturnthefirst(canonical)name. #given Thenameoftheoptionasactuallyused,unabbreveated. #ThreadSafety Getopt::LongisthreadsafewhenusingithreadsasofPerl5.8.Itisnotthreadsafewhenusingtheolder(experimentalandnowobsolete)threadsimplementationthatwasaddedtoPerl5.005. #Documentationandhelptexts Getopt::LongencouragestheuseofPod::Usagetoproducehelpmessages.Forexample: useGetopt::Long; usePod::Usage; my$man=0; my$help=0; GetOptions('help|?'=>\$help,man=>\$man)orpod2usage(2); pod2usage(1)if$help; pod2usage(-exitval=>0,-verbose=>2)if$man; __END__ =head1NAME sample-UsingGetopt::LongandPod::Usage =head1SYNOPSIS sample[options][file...] Options: -helpbriefhelpmessage -manfulldocumentation =head1OPTIONS =over8 =itemB Printabriefhelpmessageandexits. =itemB Printsthemanualpageandexits. =back =head1DESCRIPTION Bwillreadthegiveninputfile(s)anddosomething usefulwiththecontentsthereof. =cut SeePod::Usagefordetails. #Parsingoptionsfromanarbitraryarray Bydefault,GetOptionsparsestheoptionsthatarepresentintheglobalarray@ARGV.AspecialentryGetOptionsFromArraycanbeusedtoparseoptionsfromanarbitraryarray. useGetopt::Longqw(GetOptionsFromArray); $ret=GetOptionsFromArray(\@myopts,...); Whenusedlikethis,optionsandtheirpossiblevaluesareremovedfrom@myopts,theglobal@ARGVisnottouchedatall. Thefollowingtwocallsbehaveidentically: $ret=GetOptions(...); $ret=GetOptionsFromArray(\@ARGV,...); Thisalsomeansthatafirstargumenthashreferencenowbecomesthesecondargument: $ret=GetOptions(\%opts,...); $ret=GetOptionsFromArray(\@ARGV,\%opts,...); #Parsingoptionsfromanarbitrarystring AspecialentryGetOptionsFromStringcanbeusedtoparseoptionsfromanarbitrarystring. useGetopt::Longqw(GetOptionsFromString); $ret=GetOptionsFromString($string,...); ThecontentsofthestringaresplitintoargumentsusingacalltoText::ParseWords::shellwords.AswithGetOptionsFromArray,theglobal@ARGVisnottouched. Itispossiblethat,uponcompletion,notallargumentsinthestringhavebeenprocessed.GetOptionsFromStringwill,whencalledinlistcontext,returnboththereturnstatusandanarrayreferencetoanyremainingarguments: ($ret,$args)=GetOptionsFromString($string,...); Ifanyargumentsremain,andGetOptionsFromStringwasnotcalledinlistcontext,amessagewillbegivenandGetOptionsFromStringwillreturnfailure. AswithGetOptionsFromArray,afirstargumenthashreferencenowbecomesthesecondargument.Seethenextsection. #Storingoptionsvaluesinahash Sometimes,forexamplewhentherearealotofoptions,havingaseparatevariableforeachofthemcanbecumbersome.GetOptions()supports,asanalternativemechanism,storingoptionsvaluesinahash. Toobtainthis,areferencetoahashmustbepassedasthefirstargumenttoGetOptions().Foreachoptionthatisspecifiedonthecommandline,theoptionvaluewillbestoredinthehashwiththeoptionnameaskey.Optionsthatarenotactuallyusedonthecommandlinewillnotbeputinthehash,onotherwords,exists($h{option})(ordefined())canbeusedtotestifanoptionwasused.Thedrawbackisthatwarningswillbeissuediftheprogramrunsunderusestrictanduses$h{option}withouttestingwithexists()ordefined()first. my%h=(); GetOptions(\%h,'length=i'); #willstorein$h{length} Foroptionsthattakelistorhashvalues,itisnecessarytoindicatethisbyappendingan@or%signafterthetype: GetOptions(\%h,'colours=s@'); #willpushto@{$h{colours}} Tomakethingsmorecomplicated,thehashmaycontainreferencestotheactualdestinations,forexample: my$len=0; my%h=('length'=>\$len); GetOptions(\%h,'length=i'); #willstorein$len Thisexampleisfullyequivalentwith: my$len=0; GetOptions('length=i'=>\$len); #willstorein$len Anymixtureispossible.Forexample,themostfrequentlyusedoptionscouldbestoredinvariableswhileallotheroptionsgetstoredinthehash: my$verbose=0; #frequentlyreferred my$debug=0; #frequentlyreferred my%h=('verbose'=>\$verbose,'debug'=>\$debug); GetOptions(\%h,'verbose','debug','filter','size=i'); if($verbose){...} if(exists$h{filter}){...option'filter'wasspecified...} #Bundling Withbundlingitispossibletosetseveralsingle-characteroptionsatonce.Forexampleifa,vandxareallvalidoptions, -vax willsetallthree. Getopt::Longsupportsthreestylesofbundling.Toenablebundling,acalltoGetopt::Long::Configureisrequired. Thesimpleststyleofbundlingcanbeenabledwith: Getopt::Long::Configure("bundling"); Configuredthisway,single-characteroptionscanbebundledbutlongoptions(andanyoftheirauto-abbreviatedshortenedforms)mustalwaysstartwithadoubledash--toavoidambiguity.Forexample,whenvax,a,vandxareallvalidoptions, -vax willseta,vandx,but --vax willsetvax. Thesecondstyleofbundlingliftsthisrestriction.Itcanbeenabledwith: Getopt::Long::Configure("bundling_override"); Now,-vaxwillsettheoptionvax. Inalloftheabovecases,optionvaluesmaybeinsertedinthebundle.Forexample: -h24w80 isequivalentto -h24-w80 Athirdstyleofbundlingallowsonlyvaluestobebundledwithoptions.Itcanbeenabledwith: Getopt::Long::Configure("bundling_values"); Now,-h24willsettheoptionhto24,butoptionbundleslike-vxaand-h24w80areflaggedaserrors. Enablingbundling_valueswilldisabletheothertwostylesofbundling. Whenconfiguredforbundling,single-characteroptionsarematchedcasesensitivewhilelongoptionsarematchedcaseinsensitive.Tohavethesingle-characteroptionsmatchedcaseinsensitiveaswell,use: Getopt::Long::Configure("bundling","ignorecase_always"); Itgoeswithoutsayingthatbundlingcanbequiteconfusing. #Thelonesomedash Normally,alonedash-onthecommandlinewillnotbeconsideredanoption.Optionprocessingwillterminate(unless"permute"isconfigured)andthedashwillbeleftin@ARGV. Itispossibletogetspecialtreatmentforalonedash.Thiscanbeachievedbyaddinganoptionspecificationwithanemptyname,forexample: GetOptions(''=>\$stdio); Alonedashonthecommandlinewillnowbealegaloption,andusingitwillsetvariable$stdio. #Argumentcallback Aspecialoption'name'<>canbeusedtodesignateasubroutinetohandlenon-optionarguments.WhenGetOptions()encountersanargumentthatdoesnotlooklikeanoption,itwillimmediatelycallthissubroutineandpassesitoneparameter:theargumentname. Forexample: my$width=80; subprocess{...} GetOptions('width=i'=>\$width,'<>'=>\&process); Whenappliedtothefollowingcommandline: arg1--width=72arg2--width=60arg3 Thiswillcallprocess("arg1")while$widthis80,process("arg2")while$widthis72,andprocess("arg3")while$widthis60. Thisfeaturerequiresconfigurationoptionpermute,seesection"ConfiguringGetopt::Long". #ConfiguringGetopt::Long Getopt::LongcanbeconfiguredbycallingsubroutineGetopt::Long::Configure().Thissubroutinetakesalistofquotedstrings,eachspecifyingaconfigurationoptiontobeenabled,e.g.ignore_case.Todisable,prefixwithnoorno_,e.g.no_ignore_case.Casedoesnotmatter.MultiplecallstoConfigure()arepossible. Alternatively,asofversion2.24,theconfigurationoptionsmaybepassedtogetherwiththeusestatement: useGetopt::Longqw(:configno_ignore_casebundling); Thefollowingoptionsareavailable: #default Thisoptioncausesallconfigurationoptionstoberesettotheirdefaultvalues. #posix_default ThisoptioncausesallconfigurationoptionstoberesettotheirdefaultvaluesasiftheenvironmentvariablePOSIXLY_CORRECThadbeenset. #auto_abbrev Allowoptionnamestobeabbreviatedtouniqueness.DefaultisenabledunlessenvironmentvariablePOSIXLY_CORRECThasbeenset,inwhichcaseauto_abbrevisdisabled. #getopt_compat Allow+tostartoptions.DefaultisenabledunlessenvironmentvariablePOSIXLY_CORRECThasbeenset,inwhichcasegetopt_compatisdisabled. #gnu_compat gnu_compatcontrolswhether--opt=isallowed,andwhatitshoulddo.Withoutgnu_compat,--opt=givesanerror.Withgnu_compat,--opt=willgiveoptionoptandemptyvalue.ThisisthewayGNUgetopt_long()doesit. Notethat--optvalueisstillaccepted,eventhoughGNUgetopt_long()doesn't. #gnu_getopt Thisisashortwayofsettinggnu_compatbundlingpermuteno_getopt_compat.Withgnu_getopt,commandlinehandlingshouldbereasonablycompatiblewithGNUgetopt_long(). #require_order Whethercommandlineargumentsareallowedtobemixedwithoptions.DefaultisdisabledunlessenvironmentvariablePOSIXLY_CORRECThasbeenset,inwhichcaserequire_orderisenabled. Seealsopermute,whichistheoppositeofrequire_order. #permute Whethercommandlineargumentsareallowedtobemixedwithoptions.DefaultisenabledunlessenvironmentvariablePOSIXLY_CORRECThasbeenset,inwhichcasepermuteisdisabled.Notethatpermuteistheoppositeofrequire_order. Ifpermuteisenabled,thismeansthat --fooarg1--bararg2arg3 isequivalentto --foo--bararg1arg2arg3 Ifanargumentcallbackroutineisspecified,@ARGVwillalwaysbeemptyuponsuccessfulreturnofGetOptions()sincealloptionshavebeenprocessed.Theonlyexceptioniswhen--isused: --fooarg1--bararg2--arg3 Thiswillcallthecallbackroutineforarg1andarg2,andthenterminateGetOptions()leaving"arg3"in@ARGV. Ifrequire_orderisenabled,optionsprocessingterminateswhenthefirstnon-optionisencountered. --fooarg1--bararg2arg3 isequivalentto --foo--arg1--bararg2arg3 Ifpass_throughisalsoenabled,optionsprocessingwillterminateatthefirstunrecognizedoption,ornon-option,whichevercomesfirst. #bundling(default:disabled) Enablingthisoptionwillallowsingle-characteroptionstobebundled.Todistinguishbundlesfromlongoptionnames,longoptions(andanyoftheirauto-abbreviatedshortenedforms)mustbeintroducedwith--andbundleswith-. Notethat,ifyouhaveoptionsa,landall,andauto_abbrevenabled,possibleargumentsandoptionsettingsare: usingargumentsetsoption(s) ------------------------------------------ -a,--aa -l,--ll -al,-la,-ala,-all,...a,l --al,--allall Thesurprisingpartisthat--asetsoptiona(duetoautocompletion),notall. Note:disablingbundlingalsodisablesbundling_override. #bundling_override(default:disabled) Ifbundling_overrideisenabled,bundlingisenabledaswithbundlingbutnowlongoptionnamesoverrideoptionbundles. Note:disablingbundling_overridealsodisablesbundling. Note:Usingoptionbundlingcaneasilyleadtounexpectedresults,especiallywhenmixinglongoptionsandbundles.Caveatemptor. #ignore_case(default:enabled) Ifenabled,caseisignoredwhenmatchingoptionnames.If,however,bundlingisenabledaswell,singlecharacteroptionswillbetreatedcase-sensitive. Withignore_case,optionspecificationsforoptionsthatonlydifferincase,e.g.,"foo"and"Foo",willbeflaggedasduplicates. Note:disablingignore_casealsodisablesignore_case_always. #ignore_case_always(default:disabled) Whenbundlingisineffect,caseisignoredonsingle-characteroptionsalso. Note:disablingignore_case_alwaysalsodisablesignore_case. #auto_version(default:disabled) Automaticallyprovidesupportforthe--versionoptioniftheapplicationdidnotspecifyahandlerforthisoptionitself. Getopt::Longwillprovideastandardversionmessagethatincludestheprogramname,itsversion(if$main::VERSIONisdefined),andtheversionsofGetopt::LongandPerl.Themessagewillbewrittentostandardoutputandprocessingwillterminate. auto_versionwillbeenabledifthecallingprogramexplicitlyspecifiedaversionnumberhigherthan2.32intheuseorrequirestatement. #auto_help(default:disabled) Automaticallyprovidesupportforthe--helpand-?optionsiftheapplicationdidnotspecifyahandlerforthisoptionitself. Getopt::LongwillprovideahelpmessageusingmodulePod::Usage.Themessage,derivedfromtheSYNOPSISPODsection,willbewrittentostandardoutputandprocessingwillterminate. auto_helpwillbeenabledifthecallingprogramexplicitlyspecifiedaversionnumberhigherthan2.32intheuseorrequirestatement. #pass_through(default:disabled) Withpass_throughanythingthatisunknown,ambiguousorsuppliedwithaninvalidoptionwillnotbeflaggedasanerror.Insteadtheunknownoption(s)willbepassedtothecatchall<>ifpresent,otherwisethroughto@ARGV.Thismakesitpossibletowritewrapperscriptsthatprocessonlypartoftheusersuppliedcommandlinearguments,andpasstheremainingoptionstosomeotherprogram. Ifrequire_orderisenabled,optionsprocessingwillterminateatthefirstunrecognizedoption,ornon-option,whichevercomesfirstandallremainingargumentsarepassedto@ARGVinsteadofthecatchall<>ifpresent.However,ifpermuteisenabledinstead,resultscanbecomeconfusing. Notethattheoptionsterminator(default--),ifpresent,willalsobepassedthroughin@ARGV. #prefix Thestringthatstartsoptions.Ifaconstantstringisnotsufficient,seeprefix_pattern. #prefix_pattern APerlpatternthatidentifiesthestringsthatintroduceoptions.Defaultis--|-|\+unlessenvironmentvariablePOSIXLY_CORRECThasbeenset,inwhichcaseitis--|-. #long_prefix_pattern APerlpatternthatallowsthedisambiguationoflongandshortprefixes.Defaultis--. Typicallyyouonlyneedtosetthisifyouareusingnonstandardprefixesandwantsomeorallofthemtohavethesamesemanticsas'--'doesundernormalcircumstances. Forexample,settingprefix_patternto--|-|\+|\/andlong_prefix_patternto--|\/wouldaddWin32styleargumenthandling. #debug(default:disabled) Enabledebuggingoutput. #ExportableMethods #VersionMessage Thissubroutineprovidesastandardversionmessage.Itsargumentcanbe: Astringcontainingthetextofamessagetoprintbeforeprintingthestandardmessage. Anumericvaluecorrespondingtothedesiredexitstatus. Areferencetoahash. Ifmorethanoneargumentisgiventhentheentireargumentlistisassumedtobeahash.Ifahashissupplied(eitherasareferenceorasalist)itshouldcontainoneormoreelementswiththefollowingkeys: #-message #-msg Thetextofamessagetoprintimmediatelypriortoprintingtheprogram'susagemessage. #-exitval Thedesiredexitstatustopasstotheexit()function.Thisshouldbeaninteger,orelsethestring"NOEXIT"toindicatethatcontrolshouldsimplybereturnedwithoutterminatingtheinvokingprocess. #-output Areferencetoafilehandle,orthepathnameofafiletowhichtheusagemessageshouldbewritten.Thedefaultis\*STDERRunlesstheexitvalueislessthan2(inwhichcasethedefaultis\*STDOUT). Youcannottiethisroutinedirectlytoanoption,e.g.: GetOptions("version"=>\&VersionMessage); Usethisinstead: GetOptions("version"=>sub{VersionMessage()}); #HelpMessage Thissubroutineproducesastandardhelpmessage,derivedfromtheprogram'sPODsectionSYNOPSISusingPod::Usage.IttakesthesameargumentsasVersionMessage().Inparticular,youcannottieitdirectlytoanoption,e.g.: GetOptions("help"=>\&HelpMessage); Usethisinstead: GetOptions("help"=>sub{HelpMessage()}); #ReturnvaluesandErrors Configurationerrorsanderrorsintheoptiondefinitionsaresignalledusingdie()andwillterminatethecallingprogramunlessthecalltoGetopt::Long::GetOptions()wasembeddedineval{...},ordie()wastrappedusing$SIG{__DIE__}. GetOptionsreturnstruetoindicatesuccess.Itreturnsfalsewhenthefunctiondetectedoneormoreerrorsduringoptionparsing.Theseerrorsaresignalledusingwarn()andcanbetrappedwith$SIG{__WARN__}. #Legacy Theearliestdevelopmentofnewgetopt.plstartedin1990,withPerlversion4.Asaresult,itsdevelopment,andthedevelopmentofGetopt::Long,hasgonethroughseveralstages.Sincebackwardcompatibilityhasalwaysbeenextremelyimportant,thecurrentversionofGetopt::Longstillsupportsalotofconstructsthatnowadaysarenolongernecessaryorotherwiseunwanted.Thissectiondescribesbrieflysomeofthese'features'. #Defaultdestinations Whennodestinationisspecifiedforanoption,GetOptionswillstoretheresultantvalueinaglobalvariablenamedopt_XXX,whereXXXistheprimarynameofthisoption.Whenaprogramexecutesunderusestrict(recommended),thesevariablesmustbepre-declaredwithour()orusevars. our$opt_length=0; GetOptions('length=i'); #willstorein$opt_length ToyieldausablePerlvariable,charactersthatarenotpartofthesyntaxforvariablesaretranslatedtounderscores.Forexample,--fpp-struct-returnwillsetthevariable$opt_fpp_struct_return.Notethatthisvariableresidesinthenamespaceofthecallingprogram,notnecessarilymain.Forexample: GetOptions("size=i","sizes=i@"); withcommandline"-size10-sizes24-sizes48"willperformtheequivalentoftheassignments $opt_size=10; @opt_sizes=(24,48); #Alternativeoptionstarters Astringofalternativeoptionstartercharactersmaybepassedasthefirstargument(orthefirstargumentafteraleadinghashreferenceargument). my$len=0; GetOptions('/','length=i'=>$len); Nowthecommandlinemaylooklike: /length24--arg Notethattoterminateoptionsprocessingstillrequiresadoubledash--. GetOptions()willnotinterpretaleading"<>"asoptionstartersifthenextargumentisareference.Toforce""asoptionstarters,use">{'add'}.Theresultwouldbelike $list->{add}=[qw(firstsecondthird)]; Thiscanbeaccomplishedwithadestinationroutine: GetOptions('list=s%'=> sub{push(@{$list{$_[1]}},$_[2])}); #Troubleshooting #GetOptionsdoesnotreturnafalseresultwhenanoptionisnotsupplied That'swhythey'recalled'options'. #GetOptionsdoesnotsplitthecommandlinecorrectly ThecommandlineisnotsplitbyGetOptions,butbythecommandlineinterpreter(CLI).OnUnix,thisistheshell.OnWindows,itisCOMMAND.COMorCMD.EXE.OtheroperatingsystemshaveotherCLIs. ItisimportanttoknowthattheseCLIsmaybehavedifferentwhenthecommandlinecontainsspecialcharacters,inparticularquotesorbackslashes.Forexample,withUnixshellsyoucanusesinglequotes(')anddoublequotes(")togroupwordstogether.ThefollowingalternativesareequivalentonUnix: "twowords" 'twowords' two\words Incaseofdoubt,insertthefollowingstatementinfrontofyourPerlprogram: printSTDERR(join("|",@ARGV),"\n"); toverifyhowyourCLIpassestheargumentstotheprogram. #Undefinedsubroutine&main::GetOptionscalled AreyourunningWindows,anddidyouwrite useGetOpt::Long; (notethecapital'O')? #HowdoIputa"-?"optionintoaGetopt::Long? Youcanonlyobtainthisusinganalias,andGetopt::Longofatleastversion2.13. useGetopt::Long; GetOptions("help|?");#-helpand-?willbothset$opt_help Othercharactersthatcan'tappearinPerlidentifiersarealsosupportedinaliaseswithGetopt::Longofatversion2.39.Notethatthecharacters!,|,+,=,and:canonlyappearasthefirst(oronly)characterofanalias. Asofversion2.32Getopt::Longprovidesauto-help,aquickandeasywaytoaddtheoptions--helpand-?toyourprogram,andhandlethem. Seeauto_helpinsection"ConfiguringGetopt::Long". #AUTHOR JohanVromans #COPYRIGHTANDDISCLAIMER ThisprogramisCopyright1990,2015byJohanVromans.Thisprogramisfreesoftware;youcanredistributeitand/ormodifyitunderthetermsofthePerlArtisticLicenseortheGNUGeneralPublicLicenseaspublishedbytheFreeSoftwareFoundation;eitherversion2oftheLicense,or(atyouroption)anylaterversion. Thisprogramisdistributedinthehopethatitwillbeuseful,butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyofMERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNUGeneralPublicLicenseformoredetails. IfyoudonothaveacopyoftheGNUGeneralPublicLicensewritetotheFreeSoftwareFoundation,Inc.,675MassAve,Cambridge,MA02139,USA. PerldocBrowserismaintainedbyDanBook(DBOOK).PleasecontacthimviatheGitHubissuetrackeroremailregardinganyissueswiththesiteitself,search,orrenderingofdocumentation. ThePerldocumentationismaintainedbythePerl5PortersinthedevelopmentofPerl.PleasecontactthemviathePerlissuetracker,themailinglist,orIRCtoreportanyissueswiththecontentsorformatofthedocumentation.



請為這篇文章評分?