Getopt::ArgParse - MetaCPAN

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

It implements both named arguments, using Getopt::Long for parsing, and positional arguments. The class also generates help and usage messages. About grep::cpan Recent News FAQ Tools API Identities Profile Favorites Logout GitHub Twitter Google 02May201510:19:43UTC Distribution:Getopt-ArgParse Moduleversion:1.0.6 Source (raw) Browse (raw) Changes HowtoContribute Repository Issues (6) Testers (718/1/0) Kwalitee Busfactor:0 License:artistic_2 Perl:v5.8.0 Activity 24month Tools Download(30.23KB) MetaCPANExplorer Permissions Subscribetodistribution InstallInstructions Jumptoversion 1.0.6 (MYTRAMon2015-05-02) 1.0.5 (MYTRAMon2015-03-06) 1.0.4 (MYTRAMon2014-11-25) 1.0.3 (MYTRAMon2013-10-27) 1.0.2 (MYTRAMon2013-10-04) 1.0.0 (MYTRAMon2013-09-27) ' 1.0.1 (MYTRAMon2013-09-27) Diffwithversion 1.0.6 (MYTRAMon2015-05-02) 1.0.5 (MYTRAMon2015-03-06) 1.0.4 (MYTRAMon2014-11-25) 1.0.3 (MYTRAMon2013-10-27) 1.0.2 (MYTRAMon2013-10-04) 1.0.0 (MYTRAMon2013-09-27) ' 1.0.1 (MYTRAMon2013-09-27) Dependencies Getopt::Long Moo Test::Exception andpossiblyothers Reversedependencies CPANTestersList Dependencygraph Permalinks Thisversion Latestversion ++edby: 1PAUSEuser and1contributors Mytram MytraM  /  1.0.6 (MYTRAMon2015-05-02) 1.0.5 (MYTRAMon2015-03-06) 1.0.4 (MYTRAMon2014-11-25) 1.0.3 (MYTRAMon2013-10-27) 1.0.2 (MYTRAMon2013-10-04) 1.0.0 (MYTRAMon2013-09-27) ' 1.0.1 (MYTRAMon2013-09-27) Getopt-ArgParse-1.0.6 Riverstageone •1directdependent •1totaldependent 1++ 1++  / Getopt::ArgParse NAME VERSION SYNOPSIS DESCRIPTIOIN Getopt::ArgParser::Parser Constructor add_arg,add_argument,add_args,andadd_arguments parse_args argv TheNamespaceObject SubcommandSupport add_subparsers add_parser get_parser CopyingParsers copy_args copy_parsers copy UsageMessagesandRelatedMethods format_usage print_usage format_command_usage print_command_usage SEEALSO AUTHOR CONTRIBUTORS COPYRIGHTANDLICENSE NAME Getopt::ArgParse-Parsingcommandlineargumentswitharicherandmoreuser-friendlyAPIinterface,similartopython'sargparebutwithperlishextras. Inparticular,themodulesprovidesthefollowingfeatures: -generatingusagemessages -storingparsedargvaluesinanobject,whichcanbealsousedto loadconfigurationvaluesfromfilesandthereforetheabilityfor applicationstocombineconfigurationsinasingleinterface -Amoreuser-friendlyinterfacetospecifyarguments,suchas argumenttypes,argumentvaluessplit,etc. -Subcommandparsing,suchsvn -Supportingbothflagbasednamedargumentsandpositionalarguments VERSION version1.0.6 SYNOPSIS useGetopt::ArgParse; $ap=Getopt::ArgParse->new_parser( prog=>'MyProgramName', description=>'Thisisaprogram', epilog=>'Thisappearsatthebottomofusage', ); #Parseanoption:'--foovalue'or'-fvalue' $ap->add_arg('--foo','-f',required=>1); #Parseaboolean:'--bool'or'-b'usingadifferentnamefrom #theoption $ap->add_arg('--bool','-b',type=>'Bool',dest=>'boo'); #Parseapositonaloption. #Butinthiscase,betterusingsubcommand.Seebelow $ap->add_arg('command',required=>1); #$nsisalsoaccessiblevia$ap->namespace $ns=$ap->parse_args(split('','test-f1-b')); say$ns->command;#'test' say$ns->foo;#false say$ns->boo;#false say$ns->no_boo;#true-'no_'isaddedforbooleanoptions #Youcancontinuetoaddargumentsandparsethemagain #$ap->namespaceisaccumulativelypopulated #ParseanArraytypeoptionandsplitthevalueintoanarrayofvalues $ap->add_arg('--emails',type=>'Array',split=>','); $ns=$ap->parse_args(split('','[email protected],[email protected],[email protected]')); #Becausethisisanarrayoption,thisalsoallowsyoutospecifythe #optionmultipletimesandsplitting $ns=$ap->parse_args(split('','[email protected],[email protected]@perl.org')); #Belowwillprint:[email protected]|[email protected]|[email protected]|[email protected]|[email protected]|[email protected] #BecauseArraytypesareappended sayjoin('|',$ns->emails); #Parseanoptionaskey,valuepairs $ap->add_arg('--param',type=>'Pair',split=>','); $ns=$ap->parse_args(split('','--parama=1,b=2,c=3')); say$ns->param->{a};#1 say$ns->param->{b};#2 say$ns->param->{c};#3 #Youcanusechoicetorestrictvalues $ap->add_arg('--env',choices=>['dev','prod'],); #orusecase-insensitivechoices #Overridethepreviousoptionwithreset $ap->add_arg('--env',choices_i=>['dev','prod'],reset=>1); #oruseacoderef #Overridethepreviousoption $ap->add_args( '--env', choices=>sub{ die"--envinvalidvalues"if$_[0]!~/^(dev|prod)$/i; }, reset=>1, ); #subcommands $ap->add_subparsers(title=>'subcommands');#Mustbecalledtoinitializesubcommandparsing $list_parser=$ap->add_parser( 'list', help=>'Listdirectoryentries', description=>'Amultipleparagraphslongdescription.', ); $list_parser->add_args( [ '--verbose','-v', type=>'Count', help=>'Verbosity', ], [ '--depth', help=>'depth', ], ); $ns=$ap->parse_args(split('','list-v')); say$ns->current_command();#current_commandstoreslist, #Don'tusethisnameforyourownoption $ns=$ap->parse_args(split('','helplist'));#Thiswillprinttheusageforthelistcommand #helpsubcommandisautomaticallyaddedforyou say$ns->help_command();#list #Copyparsing $common_args=Getopt::ArgParse->new_parser(); $common_args->add_args( [ '--dry-run', type=>'Bool', help=>'Dryrun', ], ); $sp=$ap->add_parser( 'remove', aliases=>[qw(rm)],#progremoveorprogrm parents=>[$command_args],#progrm--dry-run ); #Orcopyexplicitly $sp=$ap->add_parser( 'copy', aliases=>[qw(cp)],#progremoveorprogrm ); $sp->copy_args($command_parser);#Youcanalsocopy_parsers()butinthiscase #$common_parserdoesn'thavesubparsers DESCRIPTIOIN Getopt::ArgParse,Getopt::ArgParse::Parserandrelatedclassestogetheraimtoprovideuser-friendlyinterfacesforwritingcommand-lineinterfaces.Ausershouldbeabletouseitwithoutlookingupthedocumentmostofthetime.Itallowsapplicationstodefineargumentspecificationsanditwillparsethemoutof@AGRVbydefaultoracommandlineifprovided.Itimplementsbothnamedarguments,usingGetopt::Longforparsing,andpositionalarguments.Theclassalsogenerateshelpandusagemessages. Theparserhasanamespaceproperty,whichisanobjectofArgParser::Namespace.Theparsedargumentvaluesarestoredinthisnamespaceproperty.Moreover,thevaluesarestoredaccumulativelywhenparse_args()iscalledmultipletimes. ThoughinspiredbyPython'sargparseandnamesandideasareborrowedfromit,thereisalotofdifferencefromthePythonone. Getopt::ArgParser::Parser Thisistheunderlyingparserthatdoestheheavylifting. Getopt::ArgParse::ParserisaMooclass. Constructor my$parser=Getopt::ArgParse->new_parser( help=>'shortdescription', description=>'longdescription', ); TheformercallsGetopt::ArgParser::Parser->newtocreateaparserobject.Theparserconstructoracceptsthefollowingparameters. AllparsersarecreatedwithapredefinedBooloption--help|-h.Theprogramcanchoosetoresetit,though. prog Theprogram'sname.Default$0. help Ashortdescriptionoftheprogram. description Alongdescriptionoftheprogram. namespace AnobjectofGetopt::ArgParse::Namespace.Anemptynamespaceiscreatedifnotprovided.Theparsedvaluesarestoredinit,andtheycanbereferedtobytheirargumentnamesasthenamespace'sproperties,e.g.$parser->namespace->boo.SeealsoGetopt::ArgParse::Namespace parser_configs TheGetopt::Longconfigurations.SeealsoGetopt::Long parents Parentparsents,whoseargumentandsubparserspecificationsthenewparserwillcopy.Seecopy()below error_prefix CustomizethemessageprefixedtoerrormessagesthrownbyGetop::ArgParse,defaultto'Getopt::ArgParse:' print_usage_if_help Setthistofalsetonotdisplayusagemessagesevenif--helpisonorthesubcommandhelpiscalled.Thedefaultbehavioristodisplayusagemessagesifhelpisset. add_arg,add_argument,add_args,andadd_arguments $parser->add_args( ['--foo',required=>1,type=>'Array',split=>','], ['boo',required=>1,nargs=>'+'], ); Theobjectmethod,arg_argorthelongerversionadd_argument,definesthespecficationofanargument.Itacceptsthefollowingparameters. add_argsoradd_arguments()istoaddmultiplemultiplearguments. nameorflags Eitheranameoralistofoptionstrings,e.g.fooor-f,--foo. Ifdestisnotspecified,thenameorthefirstoptionwithoutleadingdasheswillbeusedasthenameforretrievingvalues.Ifanameisgiven,thisargumentisapositionalargument.Otherwise,it'sanoptionargument. Hyphenscanbeusedinnamesandflags,buttheywillbereplacedwithunderscores'_'whenusedasoptionnames.Forexample: $parser->add_argument(['--dry-run',type=>'Bool']); #commandline:prog--dry-run $parser->namespace->dry_run;#Theoption'snameisdry_run Anameoroptionstringsarefollowingbynamedparamters. dest Thenameoftheattributetobeaddedtothenamespacepopulatedbyparse_args(). type=>$type Specifythetypeoftheargument.Itcanbeoneofthefollowingvalues: Scalar Theoptiontakesascalarvalue. Array Theoptiontakesalistofvalues.Theoptioncanappearmultipletimesinthecommandline.Eachvalueisappendedtothelist.It'sstoredinanarrayrefinthenamespace. Pair Theoptiontakesalistofkey-valuepairsseparatedbytheequalsign'='.It'sstoredinahashrefinthenamespace. Bool Theoptiondoesnottakeanargument.It'ssettotrueiftheoptionispresentorfalseotherwise.A'no_bool'optionisalsoavailable,whichisthenegationofbool(). Forexample: $parser->add_argument('--dry-run',type=>'Bool'); $ns=$parser->parse_args(split('','--dry-run')); print$ns->dry_run;#true print$ns->no_dry_run;#false Count Theoptiondoesnottakeanargumentanditsvaluewillbeincrementedby1everytimeitappearsonthecommandline. split splitshouldworkwithtypes'Array'and'Pair'only. splitspecifiesastringbywhichtosplittheargumentstringe.g.ifsplit=>',',a,b,cwillbesplitinto['a','b','c'].Whensplitworkswithtype'Pair',theparserwillsplittheargumentstringandthenparseeachofthemaspairs. choicesorchoices_i choicesspecifiesalistoftheallowablevaluesfortheargumentorasubroutinethatvalidatesinputvalues. choices_ispecifiesalistoftheallowablevaluesfortheargument,butcaseinsenstive,anditdoesn'tallowtouseasubroutineforvalidation. Eitherchoicesorchioces_icanbepresentorcompletelyomitted,butnotbothatthesametime. default Thevalueproducediftheargumentisabsentfromthecommandline. Onlyonevalueisallowedforscalarargumenttypes:Scalar,Count,andBool. required Whetherornotthecommand-lineoptionmaybeomitted(optionalsonly).Thishasnoeffectontypes'Bool'and'Count'.Annamedoptionismarkedbythequestionmark?inthegeneratedusage,e.g.--help,-h?showthishelpmessageandexit ThisparameterisignoredforBoolandCounttypesfortheywillalreadyhavedefaultvalues. help Abriefdescriptionofwhattheargumentdoes. metavar Anamefortheargumentinusagemessages. reset Setresettooverridetheexistingdefinitionofanoption.Thiswillclearthevalueinthenamspaceaswell. nargs-Positionaloptiononly Thisonlyinstructshowmanyargumentstheparserconsumes.Theprogramstillneedstospecifytherighttypetoachievethedesiredresult. n 1ifnotspecified ? 1or0 + 1ormore * 0ormany.Thiswillconsumetherestofarguments. parse_args $namespace=$parser->parse_args(@command_line); Thisobjectmethodacceptsalistofargumentsor@ARGVifunspecified,parsesthemforvalues,andstoresthevaluesinthenamespaceobject. Afewthingsmaybeworthnotingaboutparse_args(). First,parsingforNamedArgumentsisdonebyGetopt::Long Second,parsingforpositionalargumentstakesplaceafterthatfornamedarguments.Itwillconsumewhat'sstillleftinthecommandline. Finally,theNamespaceobjectisaccumulativelypoplulated.Ifparse_args()iscalledmultipletimestoparseanumberofcommandlines,thesamenamespaceobjectisaccumulativelypopulated.ForScalarandBooloptions,thismeansthepreviousvaluewillbeoverwrittend.ForPairandArrayoptions,valueswillbeappended.AndforaCountoption,itwilladdontopofthepreviousvalue. Inface,theprogramcanchoosetopassaalreadypopulatednamespacewhencreatingaparserobject.Thisistoallowtheprogramtopre-loadvaluestoanamespacefromconffilesbeforeparsingthecommandline. Andfinally,itdoesNOTdisplayusagemessagesiftheargumentlistisempty.Thismaybecontrarytomanyotherimplementationsofargumentparsing. argv @argv=$parser->argv;#calledafterparse_args Callthisafterparse_args()isinvokedtogettheunconsumedarguments.It'suptotheapplicationtodecidewhattodoifthereisasurplusofarguments. TheNamespaceObject Theparsedvaluesarestoredinanamespaceobject.Anyclasswiththefollowingthreemethods: *Aconstructornew() *set_attr(name=>value) *get_attr(name) canbeusedastheNamespaceclass. ThedefaultoneisGetopt::ArgParse::Namespace.Itusesautoloadtoprovideareadonlyaccessormethodusingdestnamestoaccessparsedvalues.However,thisisnotrequiredforuser-definednamespace.Sowithintheimplementation,$namespace->get_attr($dest)shouldalwaysbeused. SubcommandSupport Noteonlyonelevelofsubcommandparsingissupported.Subcommandscannothavesubcommands. Calladd_subparsers()firsttoinitializethecurrentparserforsubcommandsupport.Ahelpsubcommandiscreatedaspartoftheinitialization.Thehelpsubcommandhasthefollowingoptions: requiredpositionalarguments:COMMAND?Showtheusageforthiscommandoptionalnamedarguments:--help,-h?showthishelpmessageandexit--all,-a?Showthefullusage Calladd_parser()toaddasubparserforeachsubcommand.Usetheparserobjectreturnedbyadd_parser()toaddtheoptionstothesubcommand. Oncesubcommandsupportison,ifthefirstargumentisnotaflag,i.e.startingwithadash'-',theparser'sparse_args()willtreatitasasubcommand.Otherwise,theparserparsesforthedefinedarguments. Thenamespace'scurrent_command()willcontainthesubcommandafterparsingsuccessfully. Unlikearguments,subparserscannotbereset. add_subparsers $parser->add_subparsers( title=>'Subcommands', description=>'descriptionaboutprovidingsubcommands', ); add_subparsersmustbecalledtoinitializesubcommandsupport. title Atitlemessagetomarkthebeginningofsubcommandusageintheusagemessage description Ageneraldescriptionappearingaboutthetitle add_parser $subparser=$parser->add_parser( 'list', aliases=>[qw(ls)], help=>'shortdescription', description=>'alongone', parents=>[$common_args],#inheritcommonargsfrom #$common_args ); $command Thefirstargumentisthenameofthenewcommand. help Ashortdescriptionofthesubcommand. description Alongdescriptionofthesubcommand. aliases Anarrayreferencecontainingalistofcommandaliases. parents Anarrayreferencecontainingalistofparserswhosespecificationwillbecopiedbythenewparser. get_parser $subparser=$parser->get_parser('ls'); Returntheparserforparsingthe$aliascommandifexsist. CopyingParsers Aparsercancopyargumentspecificationorsubcommandspecifciationforexistingparsers.Ausecaseforthisisthattheprogramwantsallsubcommandstohaveacommandsetofarguments. copy_args $parser->copy_args($common_args_parser); Copyargumentspecificationfromthe$parentparser copy_parsers $parser->copy_parsers($common_args_parser); Copyparserspecificationforsubcommandsfromthe$parentparser copy $parser->copy($common_args_parser); Copybothargumentsandsubparsers. UsageMessagesandRelatedMethods format_usage $usage=$parser->format_usage; Returntheformatedusagemessageforthewholeprograminanarrayreference. print_usage $parser->print_usage; Printtheusagemesagereturnedbyformat_usage(). format_command_usage $usage=$parser->format_command_usage($subcommand); Returntheformatedusagemessageforthecommandinanarrayreference. print_command_usage $parser->print_command_usage($subcommand); Printtheusagemessagereturnedbyformat_command_usage().If$commandisnotgiven,itwillfirsttrytouse$self->namespace->help_command,whichwillbepresentforthehelpsubcommand,andthen$self->namespace->current_command. SEEALSO Getopt::LongPython'sargparse AUTHOR Mytram(originalauthor) CONTRIBUTORS RobbinBonthond(rbonthond@github)AdamPfeiffer(apinco@github) COPYRIGHTANDLICENSE ThissoftwareisCopyright(c)2015byMytram. Thisisfreesoftware,licensedunder: TheArtisticLicense2.0(GPLCompatible) × ModuleInstallInstructions ToinstallGetopt::ArgParse,copyandpastetheappropriatecommandintoyourterminal. cpanm cpanmGetopt::ArgParse CPANshell perl-MCPAN-eshell installGetopt::ArgParse Formoreinformationonmoduleinstallation,pleasevisitthedetailedCPANmoduleinstallationguide. Close × KeyboardShortcuts Global s Focussearchbar ? Bringupthishelpdialog GitHub gp Gotopullrequests gi gotogithubissues(onlyifgithubispreferredrepository) POD ga Gotoauthor gc Gotochanges gi Gotoissues gd Gotodist gr Gotorepository/SCM gs Gotosource gb Gotofilebrowse Searchterms module:(e.g.module:Plugin) distribution:(e.g.distribution:Dancerauth) author:(e.g.author:SONGMURedis) version:(e.g.version:1.00)



請為這篇文章評分?