📄 long.pm
字号:
A trivial application of this mechanism is to implement options thatare related to each other. For example: my $verbose = ''; # option variable with default value (false) GetOptions ('verbose' => \$verbose, 'quiet' => sub { $verbose = 0 });Here C<--verbose> and C<--quiet> control the same variableC<$verbose>, but with opposite values.If the subroutine needs to signal an error, it should call die() withthe desired error message as its argument. GetOptions() will catch thedie(), issue the error message, and record that an error result mustbe returned upon completion.If the text of the error message starts with an exclamation mark C<!>it is interpreted specially by GetOptions(). There is currently onespecial command implemented: C<die("!FINISH")> will cause GetOptions()to stop processing options, as if it encountered a double dash C<-->.=head2 Options with multiple namesOften it is user friendly to supply alternate mnemonic names foroptions. For example C<--height> could be an alternate name forC<--length>. Alternate names can be included in the optionspecification, separated by vertical bar C<|> characters. To implementthe above example: GetOptions ('length|height=f' => \$length);The first name is called the I<primary> name, the other names arecalled I<aliases>. When using a hash to store options, the key willalways be the primary name.Multiple alternate names are possible.=head2 Case and abbreviationsWithout additional configuration, GetOptions() will ignore the case ofoption names, and allow the options to be abbreviated to uniqueness. GetOptions ('length|height=f' => \$length, "head" => \$head);This call will allow C<--l> and C<--L> for the length option, butrequires a least C<--hea> and C<--hei> for the head and height options.=head2 Summary of Option SpecificationsEach option specifier consists of two parts: the name specificationand the argument specification.The name specification contains the name of the option, optionallyfollowed by a list of alternative names separated by vertical barcharacters. length option name is "length" length|size|l name is "length", aliases are "size" and "l"The argument specification is optional. If omitted, the option isconsidered boolean, a value of 1 will be assigned when the option isused on the command line.The argument specification can be=over 4=item !The option does not take an argument and may be negated by prefixingit with "no" or "no-". E.g. C<"foo!"> will allow C<--foo> (a value of1 will be assigned) as well as C<--nofoo> and C<--no-foo> (a value of0 will be assigned). If the option has aliases, this applies to thealiases as well.Using negation on a single letter option when bundling is in effect ispointless and will result in a warning.=item +The option does not take an argument and will be incremented by 1every time it appears on the command line. E.g. C<"more+">, when usedwith C<--more --more --more>, will increment the value three times,resulting in a value of 3 (provided it was 0 or undefined at first).The C<+> specifier is ignored if the option destination is not a scalar.=item = I<type> [ I<desttype> ] [ I<repeat> ]The option requires an argument of the given type. Supported typesare:=over 4=item sString. An arbitrary sequence of characters. It is valid for theargument to start with C<-> or C<-->.=item iInteger. An optional leading plus or minus sign, followed by asequence of digits.=item oExtended integer, Perl style. This can be either an optional leadingplus or minus sign, followed by a sequence of digits, or an octalstring (a zero, optionally followed by '0', '1', .. '7'), or ahexadecimal string (C<0x> followed by '0' .. '9', 'a' .. 'f', caseinsensitive), or a binary string (C<0b> followed by a series of '0'and '1').=item fReal number. For example C<3.14>, C<-6.23E24> and so on.=backThe I<desttype> can be C<@> or C<%> to specify that the option islist or a hash valued. This is only needed when the destination forthe option value is not otherwise specified. It should be omitted whennot needed.The I<repeat> specifies the number of values this option takes peroccurrence on the command line. It has the format C<{> [ I<min> ] [ C<,> [ I<max> ] ] C<}>.I<min> denotes the minimal number of arguments. It defaults to 1 foroptions with C<=> and to 0 for options with C<:>, see below. Note thatI<min> overrules the C<=> / C<:> semantics.I<max> denotes the maximum number of arguments. It must be at leastI<min>. If I<max> is omitted, I<but the comma is not>, there is noupper bound to the number of argument values taken.=item : I<type> [ I<desttype> ]Like C<=>, but designates the argument as optional.If omitted, an empty string will be assigned to string values options,and the value zero to numeric options.Note that if a string argument starts with C<-> or C<-->, it will beconsidered an option on itself.=item : I<number> [ I<desttype> ]Like C<:i>, but if the value is omitted, the I<number> will be assigned.=item : + [ I<desttype> ]Like C<:i>, but if the value is omitted, the current value for theoption will be incremented.=back=head1 Advanced Possibilities=head2 Object oriented interfaceGetopt::Long can be used in an object oriented way as well: use Getopt::Long; $p = new Getopt::Long::Parser; $p->configure(...configuration options...); if ($p->getoptions(...options descriptions...)) ...Configuration options can be passed to the constructor: $p = new Getopt::Long::Parser config => [...configuration options...];=head2 Thread SafetyGetopt::Long is thread safe when using ithreads as of Perl 5.8. It isI<not> thread safe when using the older (experimental and nowobsolete) threads implementation that was added to Perl 5.005.=head2 Documentation and help textsGetopt::Long encourages the use of Pod::Usage to produce helpmessages. For example: use Getopt::Long; use Pod::Usage; my $man = 0; my $help = 0; GetOptions('help|?' => \$help, man => \$man) or pod2usage(2); pod2usage(1) if $help; pod2usage(-exitstatus => 0, -verbose => 2) if $man; __END__ =head1 NAME sample - Using Getopt::Long and Pod::Usage =head1 SYNOPSIS sample [options] [file ...] Options: -help brief help message -man full documentation =head1 OPTIONS =over 8 =item B<-help> Print a brief help message and exits. =item B<-man> Prints the manual page and exits. =back =head1 DESCRIPTION B<This program> will read the given input file(s) and do something useful with the contents thereof. =cutSee L<Pod::Usage> for details.=head2 Parsing options from an arbitrary arrayBy default, GetOptions parses the options that are present in theglobal array C<@ARGV>. A special entry C<GetOptionsFromArray> can beused to parse options from an arbitrary array. use Getopt::Long qw(GetOptionsFromArray); $ret = GetOptionsFromArray(\@myopts, ...);When used like this, the global C<@ARGV> is not touched at all.The following two calls behave identically: $ret = GetOptions( ... ); $ret = GetOptionsFromArray(\@ARGV, ... );=head2 Parsing options from an arbitrary stringA special entry C<GetOptionsFromString> can be used to parse optionsfrom an arbitrary string. use Getopt::Long qw(GetOptionsFromString); $ret = GetOptionsFromString($string, ...);The contents of the string are split into arguments using a call toC<Text::ParseWords::shellwords>. As with C<GetOptionsFromArray>, theglobal C<@ARGV> is not touched.It is possible that, upon completion, not all arguments in the stringhave been processed. C<GetOptionsFromString> will, when called in listcontext, return both the return status and an array reference to anyremaining arguments: ($ret, $args) = GetOptionsFromString($string, ... );If any arguments remain, and C<GetOptionsFromString> was not called inlist context, a message will be given and C<GetOptionsFromString> willreturn failure.=head2 Storing options values in a hashSometimes, for example when there are a lot of options, having aseparate variable for each of them can be cumbersome. GetOptions()supports, as an alternative mechanism, storing options values in ahash.To obtain this, a reference to a hash must be passed I<as the firstargument> to GetOptions(). For each option that is specified on thecommand line, the option value will be stored in the hash with theoption name as key. Options that are not actually used on the commandline will not be put in the hash, on other words,C<exists($h{option})> (or defined()) can be used to test if an optionwas used. The drawback is that warnings will be issued if the programruns under C<use strict> and uses C<$h{option}> without testing withexists() or defined() first. my %h = (); GetOptions (\%h, 'length=i'); # will store in $h{length}For options that take list or hash values, it is necessary to indicatethis by appending an C<@> or C<%> sign after the type: GetOptions (\%h, 'colours=s@'); # will push to @{$h{colours}}To make things more complicated, the hash may contain references tothe actual destinations, for example: my $len = 0; my %h = ('length' => \$len); GetOptions (\%h, 'length=i'); # will store in $lenThis example is fully equivalent with: my $len = 0; GetOptions ('length=i' => \$len); # will store in $lenAny mixture is possible. For example, the most frequently used optionscould be stored in variables while all other options get stored in thehash: my $verbose = 0; # frequently referred my $debug = 0; # frequently referred my %h = ('verbose' => \$verbose, 'debug' => \$debug); GetOptions (\%h, 'verbose', 'debug', 'filter', 'size=i'); if ( $verbose ) { ... } if ( exists $h{filter} ) { ... option 'filter' was specified ... }=head2 BundlingWith bundling it is possible to set several single-character optionsat once. For example if C<a>, C<v> and C<x> are all valid options, -vaxwould set all three.Getopt::Long supports two levels of bundling. To enable bundling, acall to Getopt::Long::Configure is required.The first level of bundling can be enabled with: Getopt::Long::Configure ("bundling");Configured this way, single-character options can be bundled but longoptions B<must> always start with a double dash C<--> to avoidambiguity. For example, when C<vax>, C<a>, C<v> and C<x> are all validoptions, -vaxwould set C<a>, C<v> and C<x>, but --vaxwould set C<vax>.The second level of bundling lifts this restriction. It can be enabledwith: Getopt::Long::Configure ("bundling_override");Now, C<-vax> would set the option C<vax>.When any level of bundling is enabled, option values may be insertedin the bundle. For example: -h24w80is equivalent to -h 24 -w 80When configured for bundling, single-character options are matchedcase sensitive while long options are matched case insensitive. Tohave the single-character options matched case insensitive as well,use: Getopt::Long::Configure ("bundling", "ignorecase_always");It goes without saying that bundling can be quite confusing.=head2 The lonesome dashNormally, a lone dash C<-> on the command line will not be consideredan option. Option processing will terminate (unless "permute" isconfigured) and the dash will be left in C<@ARGV>.It is possible to get special treatment for a lone dash. This can beachieved by adding an option specification with an empty name, forexample: GetOptions ('' => \$stdio);A lone dash on the command line will now be a legal option, and usingit will set variable C<$stdio>.=head2 Argument callbackA special option 'name' C<< <> >> can be used to designate a subroutineto handle non-option arguments. When GetOptions() encounters anargument that does not look like an option, it will immediately call thissubroutine and passes it one parameter: the argument name.For example: my $width = 80; sub process { ... } GetOptions ('width=i' => \$width, '<>' => \&process);When applied to the following command line: arg1 --width=72 arg2 --width=60 arg3This will callC<process("arg1")> while C<$width> is C<80>,C<process("arg2")> while C<$width> is C<72>, andC<process("arg3")> while C<$width> is C<60>.This feature requires configuration option B<permute>, see sectionL<Configuring Getopt::Long>.=head1 Configuring Getopt::LongGetopt::Long can be configured by calling subroutineGetopt::Long::Configure(). This subroutine takes a list of quotedstrings, each specifying a configuration option to be enabled, e.g.C<ignore_case>, or disabled, e.g. C<no_ignore_case>. Case does notmatter. Multiple calls to Configure() are possible.Alternatively, as of version 2.24, the configuration options may bepassed together with the C<use> statement: use Getopt::Long qw(:config no_ignore_case bundling);The following options are available:=over 12=item defaultThis option causes all configuration options to be reset to theirdefault values.=item posix_defaultThis option causes all configuration options to be reset to theirdefault values as if the environment variable POSIXLY_CORRECT hadbeen set.=item auto_abbrevAllow optio
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -