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

📄 long.pm

📁 UNIX下perl实现代码
💻 PM
📖 第 1 页 / 共 4 页
字号:
	    local $ENV{POSIXLY_CORRECT};	    $ENV{POSIXLY_CORRECT} = 1 if $action;	    ConfigDefaults ();	}	elsif ( $try eq 'auto_abbrev' or $try eq 'autoabbrev' ) {	    $autoabbrev = $action;	}	elsif ( $try eq 'getopt_compat' ) {	    $getopt_compat = $action;	}	elsif ( $try eq 'gnu_getopt' ) {	    if ( $action ) {		$gnu_compat = 1;		$bundling = 1;		$getopt_compat = 0;		$permute = 1;	    }	}	elsif ( $try eq 'gnu_compat' ) {	    $gnu_compat = $action;	}	elsif ( $try eq 'ignorecase' or $try eq 'ignore_case' ) {	    $ignorecase = $action;	}	elsif ( $try eq 'ignore_case_always' ) {	    $ignorecase = $action ? 2 : 0;	}	elsif ( $try eq 'bundling' ) {	    $bundling = $action;	}	elsif ( $try eq 'bundling_override' ) {	    $bundling = $action ? 2 : 0;	}	elsif ( $try eq 'require_order' ) {	    $order = $action ? $REQUIRE_ORDER : $PERMUTE;	}	elsif ( $try eq 'permute' ) {	    $order = $action ? $PERMUTE : $REQUIRE_ORDER;	}	elsif ( $try eq 'pass_through' or $try eq 'passthrough' ) {	    $passthrough = $action;	}	elsif ( $try =~ /^prefix=(.+)$/ && $action ) {	    $genprefix = $1;	    # Turn into regexp. Needs to be parenthesized!	    $genprefix = "(" . quotemeta($genprefix) . ")";	    eval { '' =~ /$genprefix/; };	    Croak ("Getopt::Long: invalid pattern \"$genprefix\"") if $@;	}	elsif ( $try =~ /^prefix_pattern=(.+)$/ && $action ) {	    $genprefix = $1;	    # Parenthesize if needed.	    $genprefix = "(" . $genprefix . ")"	      unless $genprefix =~ /^\(.*\)$/;	    eval { '' =~ /$genprefix/; };	    Croak ("Getopt::Long: invalid pattern \"$genprefix\"") if $@;	}	elsif ( $try eq 'debug' ) {	    $debug = $action;	}	else {	    Croak ("Getopt::Long: unknown config parameter \"$opt\"")	}    }    $prevconfig;}# Deprecated name.sub config (@) {    Configure (@_);}# To prevent Carp from being loaded unnecessarily.sub Croak (@) {    require 'Carp.pm';    $Carp::CarpLevel = 1;    Carp::croak(@_);};################ Documentation ################=head1 NAMEGetopt::Long - Extended processing of command line options=head1 SYNOPSIS  use Getopt::Long;  $result = GetOptions (...option-descriptions...);=head1 DESCRIPTIONThe Getopt::Long module implements an extended getopt function calledGetOptions(). This function adheres to the POSIX syntax for commandline options, with GNU extensions. In general, this means that optionshave long names instead of single letters, and are introduced with adouble dash "--". Support for bundling of command line options, as wasthe case with the more traditional single-letter approach, is providedbut not enabled by default.=head1 Command Line Options, an IntroductionCommand line operated programs traditionally take their arguments fromthe command line, for example filenames or other information that theprogram needs to know. Besides arguments, these programs often takecommand line I<options> as well. Options are not necessary for theprogram to work, hence the name 'option', but are used to modify itsdefault behaviour. For example, a program could do its job quietly,but with a suitable option it could provide verbose information aboutwhat it did.Command line options come in several flavours. Historically, they arepreceded by a single dash C<->, and consist of a single letter.    -l -a -cUsually, these single-character options can be bundled:    -lacOptions can have values, the value is placed after the optioncharacter. Sometimes with whitespace in between, sometimes not:    -s 24 -s24Due to the very cryptic nature of these options, another style wasdeveloped that used long names. So instead of a cryptic C<-l> onecould use the more descriptive C<--long>. To distinguish between abundle of single-character options and a long one, two dashes are usedto precede the option name. Early implementations of long options useda plus C<+> instead. Also, option values could be specified eitherlike    --size=24or    --size 24The C<+> form is now obsolete and strongly deprecated.=head1 Getting Started with Getopt::LongGetopt::Long is the Perl5 successor of C<newgetopt.pl>. This wasthe first Perl module that provided support for handling the new styleof command line options, hence the name Getopt::Long. This modulealso supports single-character options and bundling. In this case, theoptions are restricted to alphabetic characters only, and thecharacters C<?> and C<->.To use Getopt::Long from a Perl program, you must include thefollowing line in your Perl program:    use Getopt::Long;This will load the core of the Getopt::Long module and prepare yourprogram for using it. Most of the actual Getopt::Long code is notloaded until you really call one of its functions.In the default configuration, options names may be abbreviated touniqueness, case does not matter, and a single dash is sufficient,even for long option names. Also, options may be placed betweennon-option arguments. See L<Configuring Getopt::Long> for moredetails on how to configure Getopt::Long.=head2 Simple optionsThe most simple options are the ones that take no values. Their merepresence on the command line enables the option. Popular examples are:    --all --verbose --quiet --debugHandling simple options is straightforward:    my $verbose = '';	# option variable with default value (false)    my $all = '';	# option variable with default value (false)    GetOptions ('verbose' => \$verbose, 'all' => \$all);The call to GetOptions() parses the command line arguments that arepresent in C<@ARGV> and sets the option variable to the value C<1> ifthe option did occur on the command line. Otherwise, the optionvariable is not touched. Setting the option value to true is oftencalled I<enabling> the option.The option name as specified to the GetOptions() function is calledthe option I<specification>. Later we'll see that this specificationcan contain more than just the option name. The reference to thevariable is called the option I<destination>.GetOptions() will return a true value if the command line could beprocessed successfully. Otherwise, it will write error messages toSTDERR, and return a false result.=head2 A little bit less simple optionsGetopt::Long supports two useful variants of simple options:I<negatable> options and I<incremental> options.A negatable option is specified with a exclamation mark C<!> after theoption name:    my $verbose = '';	# option variable with default value (false)    GetOptions ('verbose!' => \$verbose);Now, using C<--verbose> on the command line will enable C<$verbose>,as expected. But it is also allowed to use C<--noverbose>, which willdisable C<$verbose> by setting its value to C<0>. Using a suitabledefault value, the program can find out whether C<$verbose> is falseby default, or disabled by using C<--noverbose>.An incremental option is specified with a plus C<+> after theoption name:    my $verbose = '';	# option variable with default value (false)    GetOptions ('verbose+' => \$verbose);Using C<--verbose> on the command line will increment the value ofC<$verbose>. This way the program can keep track of how many times theoption occurred on the command line. For example, each occurrence ofC<--verbose> could increase the verbosity level of the program.=head2 Mixing command line option with other argumentsUsually programs take command line options as well as other arguments,for example, file names. It is good practice to always specify theoptions first, and the other arguments last. Getopt::Long will,however, allow the options and arguments to be mixed and 'filter out'all the options before passing the rest of the arguments to theprogram. To stop Getopt::Long from processing further arguments,insert a double dash C<--> on the command line:    --size 24 -- --allIn this example, C<--all> will I<not> be treated as an option, butpassed to the program unharmed, in C<@ARGV>.=head2 Options with valuesFor options that take values it must be specified whether the optionvalue is required or not, and what kind of value the option expects.Three kinds of values are supported: integer numbers, floating pointnumbers, and strings.If the option value is required, Getopt::Long will take thecommand line argument that follows the option and assign this to theoption variable. If, however, the option value is specified asoptional, this will only be done if that value does not look like avalid command line option itself.    my $tag = '';	# option variable with default value    GetOptions ('tag=s' => \$tag);In the option specification, the option name is followed by an equalssign C<=> and the letter C<s>. The equals sign indicates that thisoption requires a value. The letter C<s> indicates that this value isan arbitrary string. Other possible value types are C<i> for integervalues, and C<f> for floating point values. Using a colon C<:> insteadof the equals sign indicates that the option value is optional. Inthis case, if no suitable value is supplied, string valued options getan empty string C<''> assigned, while numeric options are set to C<0>.=head2 Options with multiple valuesOptions sometimes take several values. For example, a program coulduse multiple directories to search for library files:    --library lib/stdlib --library lib/extlibTo accomplish this behaviour, simply specify an array reference as thedestination for the option:    my @libfiles = ();    GetOptions ("library=s" => \@libfiles);Used with the example above, C<@libfiles> would contain two stringsupon completion: C<"lib/srdlib"> and C<"lib/extlib">, in that order.It is also possible to specify that only integer or floating pointnumbers are acceptible values.Often it is useful to allow comma-separated lists of values as well asmultiple occurrences of the options. This is easy using Perl's split()and join() operators:    my @libfiles = ();    GetOptions ("library=s" => \@libfiles);    @libfiles = split(/,/,join(',',@libfiles));Of course, it is important to choose the right separator string foreach purpose.=head2 Options with hash valuesIf the option destination is a reference to a hash, the option willtake, as value, strings of the form I<key>C<=>I<value>. The value willbe stored with the specified key in the hash.    my %defines = ();    GetOptions ("define=s" => \%defines);When used with command line options:    --define os=linux --define vendor=redhatthe hash C<%defines> will contain two keys, C<"os"> with valueC<"linux> and C<"vendor"> with value C<"redhat">.It is also possible to specify that only integer or floating pointnumbers are acceptible values. The keys are always taken to be strings.=head2 User-defined subroutines to handle optionsUltimate control over what should be done when (actually: each time)an option is encountered on the command line can be achieved bydesignating a reference to a subroutine (or an anonymous subroutine)as the option destination. When GetOptions() encounters the option, itwill call the subroutine with two arguments: the name of the option,and the value to be assigned. It is up to the subroutine to store thevalue, or do whatever it thinks is appropriate.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 exclamantion 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>.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=item !The option does not take an argument and may be negated, i.e. prefixedby "no". E.g. C<"foo!"> will allow C<--foo> (a value of 1 will beassigned) and C<--nofoo> (a value of 0 will be assigned). If theoption has aliases, this applies to the aliases 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> ]The option requires an argument of the given type. Supported typesare:=over=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 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.=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.=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...];For thread safety, each method call will acquire an exclusive lock tothe Getopt::Long module. So don't call these methods from a callbackroutine!=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;

⌨️ 快捷键说明

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