Getopt::Long - Extended processing of command line options
文章推薦指數: 80 %
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
B
延伸文章資訊
- 1PERL -- Options
If there are no digits, the null character is the separator. ... If -e is given, perl will not lo...
- 2Check For null Arguments - PerlMonks
A better way to check for particular value is defined or not, use defined function in perl. ... d...
- 3Processing command line arguments - @ARGV in Perl
In Perl @ARGV contains the raw command line arguments as passed by the user running ... If there ...
- 4Establishing a Default Value - Perl Cookbook [Book] - O'Reilly
If 0 or "0" are valid values for your variables, use defined instead: ... If 0 is a valid value f...
- 5Getopt::Long - Extended processing of command line options
To use Getopt::Long from a Perl program, you must include the following line in ... If an argumen...