📄 declare.pm
字号:
The space-separated concatenation of the elements of the array C<@ARGV>at the time a F<Getopt::Declare> object is created.=item "parameter specification" (or just "parameter")A specification of a single entity which may appear in thecommand-line. Always includes at least one syntax for the entity.Optionally may include other (I<variant>) syntaxes, one or moreI<descriptions> of the entity, and/or I<actions> to be performed whenthe entity is encountered. For example, the following is a singleparameter specification (with two variants): --window <height> x <width> Set window to <height> by <width> { setwin($width,$height); } --window <h>x<w>@<x>,<y> Set window size and centroid { setwin($w,$h,$x,$y); }=item "argument"A substring of the command-line which matches a single parameter variant.Unlike some other Getopt:: packages, in F<Getopt::Declare> an argumentmay be a single element of C<@ARGV>, or part of a single C<@ARGV> element,or the concatenation of several adjacent C<@ARGV> elements.=item "parameter definition"A specification of one actual syntax variant matched by a parameter. Alwaysconsists of a leading I<parameter flag> or I<parameter variable>,optionally followed by one or more I<parameter components> (that is,other parameter variables or I<punctuators>). In the above example, C<S<--window E<lt>heightE<gt> x E<lt>widthE<gt>>> is a parameter definition.=item "parameter flag" (or just "flag")A sequence of non-space characters which introduces a parameter. Traditionallya parameter flag begins with "-" or "--", but F<Getopt::Declare> allowsalmost any sequence of characters to be used as a flag. In the above example,C<--window> is the parameter flag.=item "parameter variable"A place-holder (within a parameter specification) for a value that will appear in any argument matching that parameter. In the above example,C<E<lt>heightE<gt>>, C<E<lt>widthE<gt>>, C<E<lt>hE<gt>>, C<E<lt>yE<gt>>,C<E<lt>xE<gt>>, and C<E<lt>yE<gt>> are all parameter variables.=item "parameter punctuator" (or just "punctuator")A literal sequence of characters (within a parameter specification)which will appear in any argument matching that parameter. In the aboveexample, the literals C<x> and C<@> are punctuators.=item "parameter description"A textual description of the purpose and/or use of a particular variant ofparameter. In the above examples, the string: Set window to <height> by <width> is a parameter description.=item "parameter action" (or just "action")A block of Perl code to be executed in response to encountering a specificparameter. In the above example: { setwin($width,$height); }is a parameter action.=item "parameter variants"One or more different syntaxes for a single parameter, all sharingthe same leading flag, but having different trailing parametervariables and/or punctuators. F<Getopt::Declare> considers all parameterdefinitions with the same leading flag to be merely variant forms ofa single "underlying" parameter. The above example shows two parametervariants for the C<--window> parameter.=back=head2 Parameter definitionsAs indicated above, a parameter specification consists of threeparts: the parameter definition, a textual description, and anyactions to be performed when the parameter is matched.The parameter definition consists of a leading flag or parametervariable, followed by any number of parameter variables orpunctuators, optionally separated by spaces. The parameter definitionis terminated by one or more tabs (at least one trailing tab I<must>be present).For example, all of the following are valid F<Getopt::Declare> parameterdefinitions: -v in=<infile> +range <from>..<to> --lines <start> - <stop> ignore bad lines <outfile> Note that each of the above examples has at least one trailing tab(even if you can't see them). Note too that this hodge-podge ofparameter styles is certainly not recommended within a single program,but is shown so as to illustrate some of the range of parameter syntaxconventions F<Getopt::Declare> supports.The spaces between components of the parameter definition are optional butsignificant, both in the definition itself and in the arguments thatthe definition may match. If there is no space between components in thespecification, then no space is allowed between corresponding argumentson the command-line. If there I<is> space between components of thespecification, then space between those components is optional on thecommand-line.For example, the C<--lines> parameter above matches: --lines1-10 --lines 1-10 --lines 1 -10 --lines 1 - 10 --lines1- 10If it were instead specified as: --lines <start>-<stop> then it would match only: --lines1-10 --lines 1-10Note that the optional nature of spaces in parameter specification implies thatflags and punctuators cannot contain the character '<' (which is taken as thedelimiter for a parameter variable) nor the character '[' (whichintroduces an optional parameter component - seeL<"Optional parameter components">).=head2 Types of parameter variablesBy default, a parameter variable will match a single blank-terminatedor comma-delimited string. For example, the parameter: -val <value> would match any of the following the arguments: -value # <value> <- "ue" -val abcd # <value> <- "abcd" -val 1234 # <value> <- "1234" -val "a value" # <value> <- "a value"It is also possible to restrict the types of values which may bematched by a given parameter variable. For example: -limit <threshold:n> Set threshold to some (real) value -count <N:i> Set count to <N> (must be an integer)If a parameter variable is suffixed with ":n", it will match anyreasonable numeric value, whilst the ":i" suffix restricts aparameter variable to only matching integer values. These two "type specifiers" are the simplest examples of a much morepowerful mechanism, which allows parameter variables to be restrictedto matching any specific regular expression. See L<"Defining newparameter variable types">.Parameter variables are treated as scalars by default, but this toocan be altered. Any parameter variable immediately followed byan ellipsis (C<...>) is treated as a list variable, and matches itsspecified type sequentially as many times as possible. For example,the parameter specification: -pages <page:i>... would match either of the following arguments: -pages 1 -pages 1 2 7 20Note that both scalar and list parameter variables are "respectful" of theflags of other parameters as well as their own trailing punctuators.For example, given the specifications: -a -b <b_list>... -c <c_list>... ; The following arguments will be parsed as indicated: -b -d -e -a # <b_list> <- ("-d", "-e") -b -d ; # <b_list> <- ("-d", ";") -c -d ; # <c_list> <- ("-d")List parameter variables are also "repectful" of the needs ofsubsequent parameter variables. That is, a parameter specificationlike: -copy <files>... <dir> will behave as expected, putting all but the last string after the C<-copy>flag into the parameter variable C<E<lt>filesE<gt>>, whilst the verylast string is assigned to C<E<lt>dirE<gt>>.=head2 Optional parameter componentsExcept for the leading flag, any part of a parameter definitionmay be made optional by placing it in square brackets.For example: +range <from> [..] [<to>]which matches any of: +range 1..10 +range 1.. +range 1 10 +range 1List parameter variables may also be made optional (the ellipsis mustfollow the parameter variable name immediately, so it goes I<inside>the square brackets): -list [<page>...]Two or more parameter components may be made jointly optional, by specifyingthem in the same pair of brackets. Optional components may also be nested. Forexample: -range <from> [.. [<to>] ]Scalar optional parameter variables (such as C<[E<lt>toE<gt>]>)are given undefined values if they are skipped duringa successful parameter match. List optional parameter variables (such asC<[E<lt>pageE<gt>...]>) are assigned an empty list if unmatched.One important use for optional punctuators is to provide abbreviatedversions of specific flags. For example: -num[eric] # Match "-num" or "-numeric" -lexic[ographic]al # Match "-lexical" or "-lexicographical" -b[ells+]w[histles] # Match "-bw" or "-bells+whistles"Note that the actual flags for these three parameters are C<-num>, C<-lexic>and C<-b>, respectively.=head2 Parameter descriptionsProviding a textual description for each parameter (or parametervariant) is optional, but strongly recommended. Apart from providing internaldocumentation, parameter descriptions are used in the automatically-generatedusage information provided by F<Getopt::Declare>.Descriptions may be placed after the tab(s) following theparameter definition and may be continued on subsequent lines,provided those lines do not contain any tabs after the firstnon-whitespace character (because any such line will instead betreated as a new parameter specification). The description isterminated by a blank line, an action specification (see below) oranother parameter specification.For example: -v Verbose mode in=<infile> Specify input file (will fail if file does not exist) +range <from>..<to> Specify range of columns to consider --lines <start> - <stop> Specify range of lines to process ignore bad lines Ignore bad lines :-) <outfile> Specify an output fileThe parameter description may also contain special directives whichalter the way in which the parameter is parsed. See the varioussubsections of L<"ADVANCED FEATURES"> for more information.=head2 ActionsEach parameter specification may also include one or more blocks ofPerl code, specified in a pair of curly brackets (which I<must> start ona new line).Each action is executed as soon as the corresponding parameter issuccessfully matched in the command-line (but see L<"Deferred actions">for a means of delaying this response).For example: -v Verbose mode { $::verbose = 1; } -q Quiet mode { $::verbose = 0; }Actions are executed (as C<do> blocks) in the package in which theF<Getopt::Declare> object containing them was created. Hence theyhave access to all package variables and functions in that namespace.In addition, each parameter variable belonging to the correspondingparameter is made available as a (block-scoped) Perl variable with thesame name. For example: +range <from>..<to> Set range { setrange($from, $to); } -list <page:i>... Specify pages to list { foreach (@page) { list($_) if $_ > 0; } }Note that scalar parameter variables become scalar Perl variables,and list parameter variables become Perl arrays.=head2 Predefined variables available in actionsWithin an action the following variables are also available:=over 4=item C<$_PARAM_>Stores the identifier of the current parameter: either the leadingflag or, if there is no leading flag, the name of the first parametervariable.=item C<%_PUNCT_>Stores the substring matched by each punctuator in the current parameter.The hash is indexed by the punctuator itself. The main purpose of this variableis to allow actions to check whether optional punctuators were in fact matched.For example: -v[erbose] Set verbose mode (doubly verbose if full word used) { if ($_PUNCT_{"erbose"}) { $verbose = 2; } else { $verbose = 1; } }=item C<%_FOUND_>This hash stores boolean values indicating whether or not a givenparameter has already been found. The hash keys are the leading flagsor parameter variables of each parameter. For instance, the followingspecification makes the C<-q> and C<-v> parameters mutually exclusive(but see L<"Parameter dependencies"> for a I<much> easier way to achievethis effect): -v Set verbose mode { die "Can't be verbose *and* quiet!\n" if $_FOUND_{"-q"}; } -q Set quiet mode { die "Can't be quiet *and* verbose!\n" if $_FOUND_{"-v"}; }For reasons that will be explained in L<"Rejection and termination">,a given parameter is not marked as found until I<after> itsassociated actions are executed. That is, C<$_FOUND_{$_PARAM_}> will not(usually) be true during a parameter action.=backNote that, although numerous other internal variables on which thegenerated parser relies are also visible within parameter actions,accessing any of them may have Dire Consequences. Moreover, theseother variables may no longer be accessible (or even present) infuture versions of F<Getopt::Declare>. All such internal variableshave names beginning with an underscore. Avoiding such variables nameswill ensure there are no conflicts between actions and the parseritself.=head2 The command-line parsing processWhenever a F<Getopt::Declare> object is created, the current command-lineis parsed by sequentially, by attempting to match each parameterin the object's specification string against the current elements in theC<@ARGV> array (but see L<"Parsing from other sources">). The orderin which parameters are tried against C<@ARGV> is determined bythree rules:=over 4=item 1.Parameters with longer flags are tried first. Hence the command-lineargument "-quiet" would be parsed as matching the parameter C<-quiet>rather than the parameter C<S<-q E<lt>stringE<gt>>>, even if the C<-q>parameter was defined first.=item 2.Parameter I<variants> with the most components arematched first. Hence the argument "-rand 12345" would be parsed as matchingthe parameter variant C<S<-rand E<lt>seedE<gt>>>, rather than thevariant C<-rand>, even if the "shorter" C<-rand> variant was defined first.=item 3.Otherwise, parameters are matched in the order they are defined.=backElements of C<@ARGV> which do not match any defined parameter are collectedduring the parse and are eventually put back into C<@ARGV>(see L<"Strict and non-strict command-line parsing">).=head1 ADVANCED FEATURES=head2 Case-insensitive parameter matchingBy default, a F<Getopt::Declare> object parses the command-line ina I<case-sensitive> manner. The C<[nocase]> directive enables a specificparameter (or, alternatively, I<all> parameters) to be matchedcase-insensitively.If a C<[nocase]> directive is included in the description of aspecific parameter variant, then that variant (only) will be matchedwithout regard for case. For example, the specification: -q Quiet mode [nocase] -v Verbose modemeans that the arguments "S<-q>" and "S<-Q>" will both match the C<-q> parameter, butthat only "S<-v>" (and I<not> "S<-V>") will match the C<-v> parameter.If a C<[nocase]> directive appears anywhere I<outside> a parameter description,then the entire specification is declared case-insensitive and all parametersdefined in that specification are matched without reagrd to case.=head2 Termination and rejectionIt is sometimes useful to be able to terminate command-lineprocessing before all arguments have been parsed. To this end,F<Getopt::Declare> provides a special local operator (C<finish>) whichmay be used within actions. The C<finish> operator takes a single optionalargument. If the argument is true (or omitted),command-line processing is terminated at once (although the currentparameter is still marked as having been successfully matched). Forexample: -- Traditional argument list terminator { finish } -no-- Use non-traditional terminator instead { $nontrad = 1; } ## Non-traditional terminator (only valid if -no-- flag seen) { finish($nontrad); }It is also possible to reject a single parameter match from within anaction (and then continue trying other candidates). This allowsactions to be used to perform more sophisticated tests on the type ofa parameter variable, or to implement complicated parameterinterdependencies.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -