⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 long.pm

📁 UNIX下perl实现代码
💻 PM
📖 第 1 页 / 共 4 页
字号:
    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 someting    useful with the contents thereof.    =cutSee L<Pod::Usage> for details.=head2 Storing options 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 in a hash.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 avoidabiguity. 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 call-backA 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 the argument as a parameter.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 option names to be abbreviated to uniqueness.Default is enabled unless environment variablePOSIXLY_CORRECT has been set, in which case C<auto_abbrev> is disabled.=item getopt_compatAllow C<+> to start options.Default is enabled unless environment variablePOSIXLY_CORRECT has been set, in which case C<getopt_compat> is disabled.=item gnu_compatC<gnu_compat> controls whether C<--opt=> is allowed, and what it shoulddo. Without C<gnu_compat>, C<--opt=> gives an error. With C<gnu_compat>,C<--opt=> will give option C<opt> and empty value.This is the way GNU getopt_long() does it.=item gnu_getoptThis is a short way of setting C<gnu_compat> C<bundling> C<permute>C<no_getopt_compat>. With C<gnu_getopt>, command line handling should befully compatible with GNU getopt_long().=item require_orderWhether command line arguments are allowed to be mixed with options.Default is disabled unless environment variablePOSIXLY_CORRECT has been set, in which case C<require_order> is enabled.See also C<permute>, which is the opposite of C<require_order>.=item permuteWhether command line arguments are allowed to be mixed with options.Default is enabled unless environment variablePOSIXLY_CORRECT has been set, in which case C<permute> is disabled.Note that C<permute> is the opposite of C<require_order>.If C<permute> is enabled, this means that    --foo arg1 --bar arg2 arg3is equivalent to    --foo --bar arg1 arg2 arg3If an argument call-back routine is specified, C<@ARGV> will always beempty upon succesful return of GetOptions() since all options have beenprocessed. The only exception is when C<--> is used:    --foo arg1 --bar arg2 -- arg3will call the call-back routine for arg1 and arg2, and terminateGetOptions() leaving C<"arg2"> in C<@ARGV>.If C<require_order> is enabled, options processingterminates when the first non-option is encountered.    --foo arg1 --bar arg2 arg3is equivalent to    --foo -- arg1 --bar arg2 arg3If C<pass_through> is also enabled, options processing will terminateat the first unrecognized option, or non-option, whichever comesfirst.=item bundling (default: disabled)Enabling this option will allow single-character options to be bundled.To distinguish bundles from long option names, long options I<must> beintroduced with C<--> and single-character options (and bundles) withC<->.Note: disabling C<bundling> also disables C<bundling_override>.=item bundling_override (default: disabled)If C<bundling_override> is enabled, bundling is enabled as withC<bundling> but now long option names override option bundles.Note: disabling C<bundling_override> also disables C<bundling>.B<Note:> Using option bundling can easily lead to unexpected results,especially when mixing long options and bundles. Caveat emptor.=item ignore_case  (default: enabled)If enabled, case is ignored when matching long option names. Singlecharacter options will be treated case-sensitive.Note: disabling C<ignore_case> also disables C<ignore_case_always>.=item ignore_case_always (default: disabled)When bundling is in effect, case is ignored on single-characteroptions also.Note: disabling C<ignore_case_always> also disables C<ignore_case>.=item pass_through (default: disabled)Options that are unknown, ambiguous or supplied with an invalid optionvalue are passed through in C<@ARGV> instead of being flagged aserrors. This makes it possible to write wrapper scripts that processonly part of the user supplied command line arguments, and pass theremaining options to some other program.If C<require_order> is enabled, options processing will terminate atthe first unrecognized option, or non-option, whichever comes first.However, if C<permute> is enabled instead, results can become confusing.=item prefixThe string that starts options. If a constant string is notsufficient, see C<prefix_pattern>.=item prefix_patternA Perl pattern that identifies the strings that introduce options.Default is C<(--|-|\+)> unless environment variablePOSIXLY_CORRECT has been set, in which case it is C<(--|-)>.=item debug (default: disabled)Enable debugging output.=back=head1 Return values and ErrorsConfiguration errors and errors in the option definitions aresignalled using die() and will terminate the calling program unlessthe call to Getopt::Long::GetOptions() was embedded in C<eval { ...}>, or die() was trapped using C<$SIG{__DIE__}>.GetOptions returns true to indicate success.It returns false when the function detected one or more errors duringoption parsing. These errors are signalled using warn() and can betrapped with C<$SIG{__WARN__}>.Errors that can't happen are signalled using Carp::croak().=head1 LegacyThe earliest development of C<newgetopt.pl> started in 1990, with Perlversion 4. As a result, its development, and the development ofGetopt::Long, has gone through several stages. Since backwardcompatibility has always been extremely important, the current versionof Getopt::Long still supports a lot of constructs that nowadays areno longer necessary or otherwise unwanted. This section describesbriefly some of these 'features'.=head2 Default destinationsWhen no destination is specified for an option, GetOptions will storethe resultant value in a global variable named C<opt_>I<XXX>, whereI<XXX> is the primary name of this option. When a progam executesunder C<use strict> (recommended), these variables must bepre-declared with our() or C<use vars>.    our $opt_length = 0;    GetOptions ('length=i');	# will store in $opt_lengthTo yield a usable Perl variable, characters that are not part of thesyntax for variables are translated to underscores. For example,C<--fpp-struct-return> will set the variableC<$opt_fpp_struct_return>. Note that this variable resides in thenamespace of the calling program, not necessarily C<main>. Forexample:    GetOptions ("size=i", "sizes=i@");with command line "-size 10 -sizes 24 -sizes 48" will perform theequivalent of the assignments    $opt_size = 10;    @opt_sizes = (24, 48);=head2 Alternative option startersA string of alternative option starter characters may be passed as thefirst argument (or the first argument after a leading hash referenceargument).    my $len = 0;    GetOptions ('/', 'length=i' => $len);Now the command line may look like:    /length 24 -- argNote that to terminate options processing still requires a double dashC<-->.GetOptions() will not interpret a leading C<< "<>" >> as option startersif the next argument is a reference. To force C<< "<" >> and C<< ">" >> asoption starters, use C<< "><" >>. Confusing? Well, B<using a starterargument is strongly deprecated> anyway.=head2 Configuration variablesPrevious versions of Getopt::Long used variables for the purpose ofconfiguring. Although manipulating these variables still work, it isstrongly encouraged to use the C<Configure> routine that was introducedin version 2.17. Besides, it is much easier.=head1 Trouble Shooting=head2 Warning: Ignoring '!' modifier for short optionThis warning is issued when the '!' modifier is applied to a short(one-character) option and bundling is in effect. E.g.,    Getopt::Long::Configure("bundling");    GetOptions("foo|f!" => \$foo);Note that older Getopt::Long versions did not issue a warning, becausethe '!' modifier was applied to the first name only. This bug wasfixed in 2.22.Solution: separate the long and short names and apply the '!' to thelong names only, e.g.,    GetOptions("foo!" => \$foo, "f" => \$foo);=head2 GetOptions does not return a false result when an option is not suppliedThat's why they're called 'options'.=head1 AUTHORJohan Vromans <jvromans@squirrel.nl>=head1 COPYRIGHT AND DISCLAIMERThis program is Copyright 2000,1990 by Johan Vromans.This program is free software; you can redistribute it and/ormodify it under the terms of the Perl Artistic License or theGNU General Public License as published by the Free SoftwareFoundation; either version 2 of the License, or (at your option) anylater version.This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See theGNU General Public License for more details.If you do not have a copy of the GNU General Public License write tothe Free Software Foundation, Inc., 675 Mass Ave, Cambridge,MA 02139, USA.=cut# Local Variables:# eval: (load-file "pod.el")# End:

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -