home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Web Server / Savant.exe / disk1 / data1.cab / Perl5 / perl5 / lib / Getopt / long.pm next >
Encoding:
Perl POD Document  |  2001-02-23  |  30.9 KB  |  1,061 lines

  1. # GetOpt::Long.pm -- POSIX compatible options parsing
  2.  
  3. # RCS Status      : $Id: GetoptLong.pm,v 2.4 1996-10-02 11:16:26+02 jv Exp $
  4. # Author          : Johan Vromans
  5. # Created On      : Tue Sep 11 15:00:12 1990
  6. # Last Modified By: Johan Vromans
  7. # Last Modified On: Wed Oct  2 11:13:12 1996
  8. # Update Count    : 500
  9. # Status          : Released
  10.  
  11. package Getopt::Long;
  12. require 5.000;
  13. require Exporter;
  14.  
  15. @ISA = qw(Exporter);
  16. @EXPORT = qw(&GetOptions $REQUIRE_ORDER $PERMUTE $RETURN_IN_ORDER);
  17. $VERSION = sprintf("%d.%02d", '$Revision: 2.4 $ ' =~ /(\d+)\.(\d+)/);
  18. use vars qw($autoabbrev $getopt_compat $ignorecase $bundling $order
  19.         $passthrough $error $debug 
  20.         $REQUIRE_ORDER $PERMUTE $RETURN_IN_ORDER
  21.         $VERSION $major_version $minor_version);
  22. use strict;
  23.  
  24. =head1 NAME
  25.  
  26. GetOptions - extended processing of command line options
  27.  
  28. =head1 SYNOPSIS
  29.  
  30.   use Getopt::Long;
  31.   $result = GetOptions (...option-descriptions...);
  32.  
  33. =head1 DESCRIPTION
  34.  
  35. The Getopt::Long module implements an extended getopt function called
  36. GetOptions(). This function adheres to the POSIX syntax for command
  37. line options, with GNU extensions. In general, this means that options
  38. have long names instead of single letters, and are introduced with a
  39. double dash "--". Support for bundling of command line options, as was
  40. the case with the more traditional single-letter approach, is provided
  41. but not enabled by default. For example, the UNIX "ps" command can be
  42. given the command line "option"
  43.  
  44.   -vax
  45.  
  46. which means the combination of B<-v>, B<-a> and B<-x>. With the new
  47. syntax B<--vax> would be a single option, probably indicating a
  48. computer architecture. 
  49.  
  50. Command line options can be used to set values. These values can be
  51. specified in one of two ways:
  52.  
  53.   --size 24
  54.   --size=24
  55.  
  56. GetOptions is called with a list of option-descriptions, each of which
  57. consists of two elements: the option specifier and the option linkage.
  58. The option specifier defines the name of the option and, optionally,
  59. the value it can take. The option linkage is usually a reference to a
  60. variable that will be set when the option is used. For example, the
  61. following call to GetOptions:
  62.  
  63.   &GetOptions("size=i" => \$offset);
  64.  
  65. will accept a command line option "size" that must have an integer
  66. value. With a command line of "--size 24" this will cause the variable
  67. $offset to get the value 24.
  68.  
  69. Alternatively, the first argument to GetOptions may be a reference to
  70. a HASH describing the linkage for the options. The following call is
  71. equivalent to the example above:
  72.  
  73.   %optctl = ("size" => \$offset);
  74.   &GetOptions(\%optctl, "size=i");
  75.  
  76. Linkage may be specified using either of the above methods, or both.
  77. Linkage specified in the argument list takes precedence over the
  78. linkage specified in the HASH.
  79.  
  80. The command line options are taken from array @ARGV. Upon completion
  81. of GetOptions, @ARGV will contain the rest (i.e. the non-options) of
  82. the command line.
  83.  
  84. Each option specifier designates the name of the option, optionally
  85. followed by an argument specifier. Values for argument specifiers are:
  86.  
  87. =over 8
  88.  
  89. =item <none>
  90.  
  91. Option does not take an argument. 
  92. The option variable will be set to 1.
  93.  
  94. =item !
  95.  
  96. Option does not take an argument and may be negated, i.e. prefixed by
  97. "no". E.g. "foo!" will allow B<--foo> (with value 1) and B<-nofoo>
  98. (with value 0).
  99. The option variable will be set to 1, or 0 if negated.
  100.  
  101. =item =s
  102.  
  103. Option takes a mandatory string argument.
  104. This string will be assigned to the option variable.
  105. Note that even if the string argument starts with B<-> or B<-->, it
  106. will not be considered an option on itself.
  107.  
  108. =item :s
  109.  
  110. Option takes an optional string argument.
  111. This string will be assigned to the option variable.
  112. If omitted, it will be assigned "" (an empty string).
  113. If the string argument starts with B<-> or B<-->, it
  114. will be considered an option on itself.
  115.  
  116. =item =i
  117.  
  118. Option takes a mandatory integer argument.
  119. This value will be assigned to the option variable.
  120. Note that the value may start with B<-> to indicate a negative
  121. value. 
  122.  
  123. =item :i
  124.  
  125. Option takes an optional integer argument.
  126. This value will be assigned to the option variable.
  127. If omitted, the value 0 will be assigned.
  128. Note that the value may start with B<-> to indicate a negative
  129. value.
  130.  
  131. =item =f
  132.  
  133. Option takes a mandatory real number argument.
  134. This value will be assigned to the option variable.
  135. Note that the value may start with B<-> to indicate a negative
  136. value.
  137.  
  138. =item :f
  139.  
  140. Option takes an optional real number argument.
  141. This value will be assigned to the option variable.
  142. If omitted, the value 0 will be assigned.
  143.  
  144. =back
  145.  
  146. A lone dash B<-> is considered an option, the corresponding option
  147. name is the empty string.
  148.  
  149. A double dash on itself B<--> signals end of the options list.
  150.  
  151. =head2 Linkage specification
  152.  
  153. The linkage specifier is optional. If no linkage is explicitly
  154. specified but a ref HASH is passed, GetOptions will place the value in
  155. the HASH. For example:
  156.  
  157.   %optctl = ();
  158.   &GetOptions (\%optctl, "size=i");
  159.  
  160. will perform the equivalent of the assignment
  161.  
  162.   $optctl{"size"} = 24;
  163.  
  164. For array options, a reference to an array is used, e.g.:
  165.  
  166.   %optctl = ();
  167.   &GetOptions (\%optctl, "sizes=i@");
  168.  
  169. with command line "-sizes 24 -sizes 48" will perform the equivalent of
  170. the assignment
  171.  
  172.   $optctl{"sizes"} = [24, 48];
  173.  
  174. For hash options (an option whose argument looks like "name=value"),
  175. a reference to a hash is used, e.g.:
  176.  
  177.   %optctl = ();
  178.   &GetOptions (\%optctl, "define=s%");
  179.  
  180. with command line "--define foo=hello --define bar=world" will perform the
  181. equivalent of the assignment
  182.  
  183.   $optctl{"define"} = {foo=>'hello', bar=>'world')
  184.  
  185. If no linkage is explicitly specified and no ref HASH is passed,
  186. GetOptions will put the value in a global variable named after the
  187. option, prefixed by "opt_". To yield a usable Perl variable,
  188. characters that are not part of the syntax for variables are
  189. translated to underscores. For example, "--fpp-struct-return" will set
  190. the variable $opt_fpp_struct_return. Note that this variable resides
  191. in the namespace of the calling program, not necessarily B<main>.
  192. For example:
  193.  
  194.   &GetOptions ("size=i", "sizes=i@");
  195.  
  196. with command line "-size 10 -sizes 24 -sizes 48" will perform the
  197. equivalent of the assignments
  198.  
  199.   $opt_size = 10;
  200.   @opt_sizes = (24, 48);
  201.  
  202. A lone dash B<-> is considered an option, the corresponding Perl
  203. identifier is $opt_ .
  204.  
  205. The linkage specifier can be a reference to a scalar, a reference to
  206. an array, a reference to a hash or a reference to a subroutine.
  207.  
  208. If a REF SCALAR is supplied, the new value is stored in the referenced
  209. variable. If the option occurs more than once, the previous value is
  210. overwritten. 
  211.  
  212. If a REF ARRAY is supplied, the new value is appended (pushed) to the
  213. referenced array. 
  214.  
  215. If a REF HASH is supplied, the option value should look like "key" or
  216. "key=value" (if the "=value" is omitted then a value of 1 is implied).
  217. In this case, the element of the referenced hash with the key "key"
  218. is assigned "value". 
  219.  
  220. If a REF CODE is supplied, the referenced subroutine is called with
  221. two arguments: the option name and the option value.
  222. The option name is always the true name, not an abbreviation or alias.
  223.  
  224. =head2 Aliases and abbreviations
  225.  
  226. The option name may actually be a list of option names, separated by
  227. "|"s, e.g. "foo|bar|blech=s". In this example, "foo" is the true name
  228. op this option. If no linkage is specified, options "foo", "bar" and
  229. "blech" all will set $opt_foo.
  230.  
  231. Option names may be abbreviated to uniqueness, depending on
  232. configuration variable $Getopt::Long::autoabbrev.
  233.  
  234. =head2 Non-option call-back routine
  235.  
  236. A special option specifier, <>, can be used to designate a subroutine
  237. to handle non-option arguments. GetOptions will immediately call this
  238. subroutine for every non-option it encounters in the options list.
  239. This subroutine gets the name of the non-option passed.
  240. This feature requires $Getopt::Long::order to have the value $PERMUTE.
  241. See also the examples.
  242.  
  243. =head2 Option starters
  244.  
  245. On the command line, options can start with B<-> (traditional), B<-->
  246. (POSIX) and B<+> (GNU, now being phased out). The latter is not
  247. allowed if the environment variable B<POSIXLY_CORRECT> has been
  248. defined.
  249.  
  250. Options that start with "--" may have an argument appended, separated
  251. with an "=", e.g. "--foo=bar".
  252.  
  253. =head2 Return value
  254.  
  255. A return status of 0 (false) indicates that the function detected
  256. one or more errors.
  257.  
  258. =head1 COMPATIBILITY
  259.  
  260. Getopt::Long::GetOptions() is the successor of
  261. B<newgetopt.pl> that came with Perl 4. It is fully upward compatible.
  262. In fact, the Perl 5 version of newgetopt.pl is just a wrapper around
  263. the module.
  264.  
  265. If an "@" sign is appended to the argument specifier, the option is
  266. treated as an array. Value(s) are not set, but pushed into array
  267. @opt_name. If explicit linkage is supplied, this must be a reference
  268. to an ARRAY.
  269.  
  270. If an "%" sign is appended to the argument specifier, the option is
  271. treated as a hash. Value(s) of the form "name=value" are set by
  272. setting the element of the hash %opt_name with key "name" to "value"
  273. (if the "=value" portion is omitted it defaults to 1). If explicit
  274. linkage is supplied, this must be a reference to a HASH.
  275.  
  276. If configuration variable $Getopt::Long::getopt_compat is set to a
  277. non-zero value, options that start with "+" or "-" may also include their
  278. arguments, e.g. "+foo=bar". This is for compatiblity with older
  279. implementations of the GNU "getopt" routine.
  280.  
  281. If the first argument to GetOptions is a string consisting of only
  282. non-alphanumeric characters, it is taken to specify the option starter
  283. characters. Everything starting with one of these characters from the
  284. starter will be considered an option. B<Using a starter argument is
  285. strongly deprecated.>
  286.  
  287. For convenience, option specifiers may have a leading B<-> or B<-->,
  288. so it is possible to write:
  289.  
  290.    GetOptions qw(-foo=s --bar=i --ar=s);
  291.  
  292. =head1 EXAMPLES
  293.  
  294. If the option specifier is "one:i" (i.e. takes an optional integer
  295. argument), then the following situations are handled:
  296.  
  297.    -one -two        -> $opt_one = '', -two is next option
  298.    -one -2        -> $opt_one = -2
  299.  
  300. Also, assume specifiers "foo=s" and "bar:s" :
  301.  
  302.    -bar -xxx        -> $opt_bar = '', '-xxx' is next option
  303.    -foo -bar        -> $opt_foo = '-bar'
  304.    -foo --        -> $opt_foo = '--'
  305.  
  306. In GNU or POSIX format, option names and values can be combined:
  307.  
  308.    +foo=blech        -> $opt_foo = 'blech'
  309.    --bar=        -> $opt_bar = ''
  310.    --bar=--        -> $opt_bar = '--'
  311.  
  312. Example of using variable references:
  313.  
  314.    $ret = &GetOptions ('foo=s', \$foo, 'bar=i', 'ar=s', \@ar);
  315.  
  316. With command line options "-foo blech -bar 24 -ar xx -ar yy" 
  317. this will result in:
  318.  
  319.    $bar = 'blech'
  320.    $opt_bar = 24
  321.    @ar = ('xx','yy')
  322.  
  323. Example of using the <> option specifier:
  324.  
  325.    @ARGV = qw(-foo 1 bar -foo 2 blech);
  326.    &GetOptions("foo=i", \$myfoo, "<>", \&mysub);
  327.  
  328. Results:
  329.  
  330.    &mysub("bar") will be called (with $myfoo being 1)
  331.    &mysub("blech") will be called (with $myfoo being 2)
  332.  
  333. Compare this with:
  334.  
  335.    @ARGV = qw(-foo 1 bar -foo 2 blech);
  336.    &GetOptions("foo=i", \$myfoo);
  337.  
  338. This will leave the non-options in @ARGV:
  339.  
  340.    $myfoo -> 2
  341.    @ARGV -> qw(bar blech)
  342.  
  343. =head1 CONFIGURATION VARIABLES
  344.  
  345. The following variables can be set to change the default behaviour of
  346. GetOptions():
  347.  
  348. =over 12
  349.  
  350. =item $Getopt::Long::autoabbrev      
  351.  
  352. Allow option names to be abbreviated to uniqueness.
  353. Default is 1 unless environment variable
  354. POSIXLY_CORRECT has been set.
  355.  
  356. =item $Getopt::Long::getopt_compat   
  357.  
  358. Allow '+' to start options.
  359. Default is 1 unless environment variable
  360. POSIXLY_CORRECT has been set.
  361.  
  362. =item $Getopt::Long::order           
  363.  
  364. Whether non-options are allowed to be mixed with
  365. options.
  366. Default is $REQUIRE_ORDER if environment variable
  367. POSIXLY_CORRECT has been set, $PERMUTE otherwise.
  368.  
  369. $PERMUTE means that 
  370.  
  371.     -foo arg1 -bar arg2 arg3
  372.  
  373. is equivalent to
  374.  
  375.     -foo -bar arg1 arg2 arg3
  376.  
  377. If a non-option call-back routine is specified, @ARGV will always be
  378. empty upon succesful return of GetOptions since all options have been
  379. processed, except when B<--> is used:
  380.  
  381.     -foo arg1 -bar arg2 -- arg3
  382.  
  383. will call the call-back routine for arg1 and arg2, and terminate
  384. leaving arg2 in @ARGV.
  385.  
  386. If $Getopt::Long::order is $REQUIRE_ORDER, options processing
  387. terminates when the first non-option is encountered.
  388.  
  389.     -foo arg1 -bar arg2 arg3
  390.  
  391. is equivalent to
  392.  
  393.     -foo -- arg1 -bar arg2 arg3
  394.  
  395. $RETURN_IN_ORDER is not supported by GetOptions().
  396.  
  397. =item $Getopt::Long::bundling
  398.  
  399. Setting this variable to a non-zero value will allow single-character
  400. options to be bundled. To distinguish bundles from long option names,
  401. long options must be introduced with B<--> and single-character
  402. options (and bundles) with B<->. For example,
  403.  
  404.     ps -vax --vax
  405.  
  406. would be equivalent to
  407.  
  408.     ps -v -a -x --vax
  409.  
  410. provided "vax", "v", "a" and "x" have been defined to be valid
  411. options. 
  412.  
  413. Bundled options can also include a value in the bundle; this value has
  414. to be the last part of the bundle, e.g.
  415.  
  416.     scale -h24 -w80
  417.  
  418. is equivalent to
  419.  
  420.     scale -h 24 -w 80
  421.  
  422. B<Note:> Using option bundling can easily lead to unexpected results,
  423. especially when mixing long options and bundles. Caveat emptor.
  424.  
  425. =item $Getopt::Long::ignorecase
  426.  
  427. Ignore case when matching options. Default is 1. When bundling is in
  428. effect, case is ignored on single-character options only if
  429. $Getopt::Long::ignorecase is greater than 1.
  430.  
  431. =item $Getopt::Long::passthrough
  432.  
  433. Unknown options are passed through in @ARGV instead of being flagged
  434. as errors. This makes it possible to write wrapper scripts that
  435. process only part of the user supplied options, and passes the
  436. remaining options to some other program.
  437.  
  438. This can be very confusing, especially when $Getopt::Long::order is
  439. set to $PERMUTE.
  440.  
  441. =item $Getopt::Long::VERSION
  442.  
  443. The version number of this Getopt::Long implementation in the format
  444. C<major>.C<minor>. This can be used to have Exporter check the
  445. version, e.g.
  446.  
  447.     use Getopt::Long 2.00;
  448.  
  449. You can inspect $Getopt::Long::major_version and
  450. $Getopt::Long::minor_version for the individual components.
  451.  
  452. =item $Getopt::Long::error
  453.  
  454. Internal error flag. May be incremented from a call-back routine to
  455. cause options parsing to fail.
  456.  
  457. =item $Getopt::Long::debug           
  458.  
  459. Enable copious debugging output. Default is 0.
  460.  
  461. =back
  462.  
  463. =cut
  464.  
  465. ################ Introduction ################
  466. #
  467. # This program is Copyright 1990,1996 by Johan Vromans.
  468. # This program is free software; you can redistribute it and/or
  469. # modify it under the terms of the GNU General Public License
  470. # as published by the Free Software Foundation; either version 2
  471. # of the License, or (at your option) any later version.
  472. # This program is distributed in the hope that it will be useful,
  473. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  474. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  475. # GNU General Public License for more details.
  476. # If you do not have a copy of the GNU General Public License write to
  477. # the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, 
  478. # MA 02139, USA.
  479.  
  480. ################ Configuration Section ################
  481.  
  482. # Values for $order. See GNU getopt.c for details.
  483. ($REQUIRE_ORDER, $PERMUTE, $RETURN_IN_ORDER) = (0..2);
  484.  
  485. my $gen_prefix;            # generic prefix (option starters)
  486.  
  487. # Handle POSIX compliancy.
  488. if ( defined $ENV{"POSIXLY_CORRECT"} ) {
  489.     $gen_prefix = "(--|-)";
  490.     $autoabbrev = 0;        # no automatic abbrev of options
  491.     $bundling = 0;        # no bundling of single letter switches
  492.     $getopt_compat = 0;        # disallow '+' to start options
  493.     $order = $REQUIRE_ORDER;
  494. }
  495. else {
  496.     $gen_prefix = "(--|-|\\+)";
  497.     $autoabbrev = 1;        # automatic abbrev of options
  498.     $bundling = 0;        # bundling off by default
  499.     $getopt_compat = 1;        # allow '+' to start options
  500.     $order = $PERMUTE;
  501. }
  502.  
  503. # Other configurable settings.
  504. $debug = 0;            # for debugging
  505. $error = 0;            # error tally
  506. $ignorecase = 1;        # ignore case when matching options
  507. $passthrough = 0;        # leave unrecognized options alone
  508. ($major_version, $minor_version) = $VERSION =~ /^(\d+)\.(\d+)/;
  509.  
  510. use vars qw($genprefix %opctl @opctl %bopctl $opt $arg $argend $array);
  511. use vars qw(%aliases $hash $key);
  512.  
  513. ################ Subroutines ################
  514.  
  515. sub GetOptions {
  516.  
  517.     my @optionlist = @_;    # local copy of the option descriptions
  518.     local ($argend) = '--';        # option list terminator
  519.     local (%opctl);            # table of arg.specs (long and abbrevs)
  520.     local (%bopctl);            # table of arg.specs (bundles)
  521.     my $pkg = (caller)[0];    # current context
  522.                 # Needed if linkage is omitted.
  523.     local (%aliases);        # alias table
  524.     my @ret = ();        # accum for non-options
  525.     my %linkage;        # linkage
  526.     my $userlinkage;        # user supplied HASH
  527.     local ($genprefix) = $gen_prefix; # so we can call the same module more 
  528.                 # than once in differing environments
  529.     $error = 0;
  530.  
  531.     print STDERR ('GetOptions $Revision: 2.4 $ ',
  532.           "[GetOpt::Long $Getopt::Long::VERSION] -- ",
  533.           "called from package \"$pkg\".\n",
  534.           "  (@ARGV)\n",
  535.           "  autoabbrev=$autoabbrev".
  536.           ",bundling=$bundling",
  537.           ",getopt_compat=$getopt_compat",
  538.           ",order=$order",
  539.           ",\n  ignorecase=$ignorecase",
  540.           ",passthrough=$passthrough",
  541.           ",genprefix=\"$genprefix\"",
  542.           ".\n")
  543.     if $debug;
  544.  
  545.     # Check for ref HASH as first argument. 
  546.     $userlinkage = undef;
  547.     if ( ref($optionlist[0]) && ref($optionlist[0]) eq 'HASH' ) {
  548.     $userlinkage = shift (@optionlist);
  549.     }
  550.  
  551.     # See if the first element of the optionlist contains option
  552.     # starter characters.
  553.     if ( $optionlist[0] =~ /^\W+$/ ) {
  554.     $genprefix = shift (@optionlist);
  555.     # Turn into regexp.
  556.     $genprefix =~ s/(\W)/\\$1/g;
  557.     $genprefix = "[" . $genprefix . "]";
  558.     }
  559.  
  560.     # Verify correctness of optionlist.
  561.     %opctl = ();
  562.     %bopctl = ();
  563.     while ( @optionlist > 0 ) {
  564.     my $opt = shift (@optionlist);
  565.  
  566.     # Strip leading prefix so people can specify "--foo=i" if they like.
  567.     $opt = $' if $opt =~ /^($genprefix)+/;
  568.  
  569.     if ( $opt eq '<>' ) {
  570.         if ( (defined $userlinkage)
  571.         && !(@optionlist > 0 && ref($optionlist[0]))
  572.         && (exists $userlinkage->{$opt})
  573.         && ref($userlinkage->{$opt}) ) {
  574.         unshift (@optionlist, $userlinkage->{$opt});
  575.         }
  576.         unless ( @optionlist > 0 
  577.             && ref($optionlist[0]) && ref($optionlist[0]) eq 'CODE' ) {
  578.         warn ("Option spec <> requires a reference to a subroutine\n");
  579.         $error++;
  580.         next;
  581.         }
  582.         $linkage{'<>'} = shift (@optionlist);
  583.         next;
  584.     }
  585.  
  586.     if ( $opt !~ /^(\w+[-\w|]*)?(!|[=:][infse][@%]?)?$/ ) {
  587.         warn ("Error in option spec: \"", $opt, "\"\n");
  588.         $error++;
  589.         next;
  590.     }
  591.     my ($o, $c, $a) = ($1, $2);
  592.     $c = '' unless defined $c;
  593.  
  594.     if ( ! defined $o ) {
  595.         # empty -> '-' option
  596.         $opctl{$o = ''} = $c;
  597.     }
  598.     else {
  599.         # Handle alias names
  600.         my @o =  split (/\|/, $o);
  601.         my $linko = $o = $o[0];
  602.         # Force an alias if the option name is not locase.
  603.         $a = $o unless $o eq lc($o);
  604.         $o = lc ($o)
  605.         if $ignorecase > 1 
  606.             || ($ignorecase
  607.             && ($bundling ? length($o) > 1  : 1));
  608.  
  609.         foreach ( @o ) {
  610.         if ( $bundling && length($_) == 1 ) {
  611.             $_ = lc ($_) if $ignorecase > 1;
  612.             if ( $c eq '!' ) {
  613.             $opctl{"no$_"} = $c;
  614.             warn ("Ignoring '!' modifier for short option $_\n");
  615.             $c = '';
  616.             }
  617.             $bopctl{$_} = $c;
  618.         }
  619.         else {
  620.             $_ = lc ($_) if $ignorecase;
  621.             if ( $c eq '!' ) {
  622.             $opctl{"no$_"} = $c;
  623.             $c = '';
  624.             }
  625.             $opctl{$_} = $c;
  626.         }
  627.         if ( defined $a ) {
  628.             # Note alias.
  629.             $aliases{$_} = $a;
  630.         }
  631.         else {
  632.             # Set primary name.
  633.             $a = $_;
  634.         }
  635.         }
  636.         $o = $linko;
  637.     }
  638.  
  639.     # If no linkage is supplied in the @optionlist, copy it from
  640.     # the userlinkage if available.
  641.     if ( defined $userlinkage ) {
  642.         unless ( @optionlist > 0 && ref($optionlist[0]) ) {
  643.         if ( exists $userlinkage->{$o} && ref($userlinkage->{$o}) ) {
  644.             print STDERR ("=> found userlinkage for \"$o\": ",
  645.                   "$userlinkage->{$o}\n")
  646.             if $debug;
  647.             unshift (@optionlist, $userlinkage->{$o});
  648.         }
  649.         else {
  650.             # Do nothing. Being undefined will be handled later.
  651.             next;
  652.         }
  653.         }
  654.     }
  655.  
  656.     # Copy the linkage. If omitted, link to global variable.
  657.     if ( @optionlist > 0 && ref($optionlist[0]) ) {
  658.         print STDERR ("=> link \"$o\" to $optionlist[0]\n")
  659.         if $debug;
  660.         if ( ref($optionlist[0]) =~ /^(SCALAR|CODE)$/ ) {
  661.         $linkage{$o} = shift (@optionlist);
  662.         }
  663.         elsif ( ref($optionlist[0]) =~ /^(ARRAY)$/ ) {
  664.         $linkage{$o} = shift (@optionlist);
  665.         $opctl{$o} .= '@' unless $opctl{$o} =~ /\@$/;
  666.         }
  667.         elsif ( ref($optionlist[0]) =~ /^(HASH)$/ ) {
  668.         $linkage{$o} = shift (@optionlist);
  669.         $opctl{$o} .= '%' unless $opctl{$o} =~ /\%$/;
  670.         }
  671.         else {
  672.         warn ("Invalid option linkage for \"", $opt, "\"\n");
  673.         $error++;
  674.         }
  675.     }
  676.     else {
  677.         # Link to global $opt_XXX variable.
  678.         # Make sure a valid perl identifier results.
  679.         my $ov = $o;
  680.         $ov =~ s/\W/_/g;
  681.         if ( $c =~ /@/ ) {
  682.         print STDERR ("=> link \"$o\" to \@$pkg","::opt_$ov\n")
  683.             if $debug;
  684.         eval ("\$linkage{\$o} = \\\@".$pkg."::opt_$ov;");
  685.         }
  686.         elsif ( $c =~ /%/ ) {
  687.         print STDERR ("=> link \"$o\" to \%$pkg","::opt_$ov\n")
  688.             if $debug;
  689.         eval ("\$linkage{\$o} = \\\%".$pkg."::opt_$ov;");
  690.         }
  691.         else {
  692.         print STDERR ("=> link \"$o\" to \$$pkg","::opt_$ov\n")
  693.             if $debug;
  694.         eval ("\$linkage{\$o} = \\\$".$pkg."::opt_$ov;");
  695.         }
  696.     }
  697.     }
  698.  
  699.     # Bail out if errors found.
  700.     return 0 if $error;
  701.  
  702.     # Sort the possible long option names.
  703.     local (@opctl) = sort(keys (%opctl)) if $autoabbrev;
  704.  
  705.     # Show the options tables if debugging.
  706.     if ( $debug ) {
  707.     my ($arrow, $k, $v);
  708.     $arrow = "=> ";
  709.     while ( ($k,$v) = each(%opctl) ) {
  710.         print STDERR ($arrow, "\$opctl{\"$k\"} = \"$v\"\n");
  711.         $arrow = "   ";
  712.     }
  713.     $arrow = "=> ";
  714.     while ( ($k,$v) = each(%bopctl) ) {
  715.         print STDERR ($arrow, "\$bopctl{\"$k\"} = \"$v\"\n");
  716.         $arrow = "   ";
  717.     }
  718.     }
  719.  
  720.     local ($opt);            # current option
  721.     local ($arg);            # current option value, if any
  722.     local ($array);            # current option is array typed
  723.     local ($hash);            # current option is hash typed
  724.     local ($key);            # hash key for a hash option
  725.  
  726.     # Process argument list
  727.     while ( @ARGV > 0 ) {
  728.  
  729.     #### Get next argument ####
  730.  
  731.     $opt = shift (@ARGV);
  732.     $arg = undef;
  733.     $array = $hash = 0;
  734.     print STDERR ("=> option \"", $opt, "\"\n") if $debug;
  735.  
  736.     #### Determine what we have ####
  737.  
  738.     # Double dash is option list terminator.
  739.     if ( $opt eq $argend ) {
  740.         # Finish. Push back accumulated arguments and return.
  741.         unshift (@ARGV, @ret) 
  742.         if $order == $PERMUTE;
  743.         return ($error == 0);
  744.     }
  745.  
  746.     my $tryopt = $opt;
  747.  
  748.     # find_option operates on the GLOBAL $opt and $arg!
  749.     if ( &find_option ) {
  750.         
  751.         # find_option undefines $opt in case of errors.
  752.         next unless defined $opt;
  753.  
  754.         if ( defined $arg ) {
  755.         $opt = $aliases{$opt} if defined $aliases{$opt};
  756.  
  757.         if ( defined $linkage{$opt} ) {
  758.             print STDERR ("=> ref(\$L{$opt}) -> ",
  759.                   ref($linkage{$opt}), "\n") if $debug;
  760.  
  761.             if ( ref($linkage{$opt}) eq 'SCALAR' ) {
  762.             print STDERR ("=> \$\$L{$opt} = \"$arg\"\n") if $debug;
  763.             ${$linkage{$opt}} = $arg;
  764.             }
  765.             elsif ( ref($linkage{$opt}) eq 'ARRAY' ) {
  766.             print STDERR ("=> push(\@{\$L{$opt}, \"$arg\")\n")
  767.                 if $debug;
  768.             push (@{$linkage{$opt}}, $arg);
  769.             }
  770.             elsif ( ref($linkage{$opt}) eq 'HASH' ) {
  771.             print STDERR ("=> \$\$L{$opt}->{$key} = \"$arg\"\n")
  772.                 if $debug;
  773.             $linkage{$opt}->{$key} = $arg;
  774.             }
  775.             elsif ( ref($linkage{$opt}) eq 'CODE' ) {
  776.             print STDERR ("=> &L{$opt}(\"$opt\", \"$arg\")\n")
  777.                 if $debug;
  778.             &{$linkage{$opt}}($opt, $arg);
  779.             }
  780.             else {
  781.             print STDERR ("Invalid REF type \"", ref($linkage{$opt}),
  782.                       "\" in linkage\n");
  783.             die ("Getopt::Long -- internal error!\n");
  784.             }
  785.         }
  786.         # No entry in linkage means entry in userlinkage.
  787.         elsif ( $array ) {
  788.             if ( defined $userlinkage->{$opt} ) {
  789.             print STDERR ("=> push(\@{\$L{$opt}}, \"$arg\")\n")
  790.                 if $debug;
  791.             push (@{$userlinkage->{$opt}}, $arg);
  792.             }
  793.             else {
  794.             print STDERR ("=>\$L{$opt} = [\"$arg\"]\n")
  795.                 if $debug;
  796.             $userlinkage->{$opt} = [$arg];
  797.             }
  798.         }
  799.         elsif ( $hash ) {
  800.             if ( defined $userlinkage->{$opt} ) {
  801.             print STDERR ("=> \$L{$opt}->{$key} = \"$arg\"\n")
  802.                 if $debug;
  803.             $userlinkage->{$opt}->{$key} = $arg;
  804.             }
  805.             else {
  806.             print STDERR ("=>\$L{$opt} = {$key => \"$arg\"}\n")
  807.                 if $debug;
  808.             $userlinkage->{$opt} = {$key => $arg};
  809.             }
  810.         }
  811.         else {
  812.             print STDERR ("=>\$L{$opt} = \"$arg\"\n") if $debug;
  813.             $userlinkage->{$opt} = $arg;
  814.         }
  815.         }
  816.     }
  817.  
  818.     # Not an option. Save it if we $PERMUTE and don't have a <>.
  819.     elsif ( $order == $PERMUTE ) {
  820.         # Try non-options call-back.
  821.         my $cb;
  822.         if ( (defined ($cb = $linkage{'<>'})) ) {
  823.         &$cb($tryopt);
  824.         }
  825.         else {
  826.         print STDERR ("=> saving \"$tryopt\" ",
  827.                   "(not an option, may permute)\n") if $debug;
  828.         push (@ret, $tryopt);
  829.         }
  830.         next;
  831.     }
  832.  
  833.     # ...otherwise, terminate.
  834.     else {
  835.         # Push this one back and exit.
  836.         unshift (@ARGV, $tryopt);
  837.         return ($error == 0);
  838.     }
  839.  
  840.     }
  841.  
  842.     # Finish.
  843.     if ( $order == $PERMUTE ) {
  844.     #  Push back accumulated arguments
  845.     print STDERR ("=> restoring \"", join('" "', @ret), "\"\n")
  846.         if $debug && @ret > 0;
  847.     unshift (@ARGV, @ret) if @ret > 0;
  848.     }
  849.  
  850.     return ($error == 0);
  851. }
  852.  
  853. sub find_option {
  854.  
  855.     return 0 unless $opt =~ /^$genprefix/;
  856.  
  857.     $opt = $';
  858.     my ($starter) = $&;
  859.  
  860.     my $optarg = undef;    # value supplied with --opt=value
  861.     my $rest = undef;    # remainder from unbundling
  862.  
  863.     # If it is a long option, it may include the value.
  864.     if (($starter eq "--" || $getopt_compat)
  865.     && $opt =~ /^([^=]+)=/ ) {
  866.     $opt = $1;
  867.     $optarg = $';
  868.     print STDERR ("=> option \"", $opt, 
  869.               "\", optarg = \"$optarg\"\n") if $debug;
  870.     }
  871.  
  872.     #### Look it up ###
  873.  
  874.     my $tryopt = $opt;        # option to try
  875.     my $optbl = \%opctl;    # table to look it up (long names)
  876.  
  877.     if ( $bundling && $starter eq '-' ) {
  878.     # Unbundle single letter option.
  879.     $rest = substr ($tryopt, 1);
  880.     $tryopt = substr ($tryopt, 0, 1);
  881.     $tryopt = lc ($tryopt) if $ignorecase > 1;
  882.     print STDERR ("=> $starter$tryopt unbundled from ",
  883.               "$starter$tryopt$rest\n") if $debug;
  884.     $rest = undef unless $rest ne '';
  885.     $optbl = \%bopctl;    # look it up in the short names table
  886.     } 
  887.  
  888.     # Try auto-abbreviation.
  889.     elsif ( $autoabbrev ) {
  890.     # Downcase if allowed.
  891.     $tryopt = $opt = lc ($opt) if $ignorecase;
  892.     # Turn option name into pattern.
  893.     my $pat = quotemeta ($opt);
  894.     # Look up in option names.
  895.     my @hits = grep (/^$pat/, @opctl);
  896.     print STDERR ("=> ", scalar(@hits), " hits (@hits) with \"$pat\" ",
  897.               "out of ", scalar(@opctl), "\n") if $debug;
  898.  
  899.     # Check for ambiguous results.
  900.     unless ( (@hits <= 1) || (grep ($_ eq $opt, @hits) == 1) ) {
  901.         # See if all matches are for the same option.
  902.         my %hit;
  903.         foreach ( @hits ) {
  904.         $_ = $aliases{$_} if defined $aliases{$_};
  905.         $hit{$_} = 1;
  906.         }
  907.         # Now see if it really is ambiguous.
  908.         unless ( keys(%hit) == 1 ) {
  909.         return 0 if $passthrough;
  910.         print STDERR ("Option ", $opt, " is ambiguous (",
  911.                   join(", ", @hits), ")\n");
  912.         $error++;
  913.         undef $opt;
  914.         return 1;
  915.         }
  916.         @hits = keys(%hit);
  917.     }
  918.  
  919.     # Complete the option name, if appropriate.
  920.     if ( @hits == 1 && $hits[0] ne $opt ) {
  921.         $tryopt = $hits[0];
  922.         $tryopt = lc ($tryopt) if $ignorecase;
  923.         print STDERR ("=> option \"$opt\" -> \"$tryopt\"\n")
  924.         if $debug;
  925.     }
  926.     }
  927.  
  928.     # Check validity by fetching the info.
  929.     my $type = $optbl->{$tryopt};
  930.     unless  ( defined $type ) {
  931.     return 0 if $passthrough;
  932.     warn ("Unknown option: ", $opt, "\n");
  933.     $error++;
  934.     return 1;
  935.     }
  936.     # Apparently valid.
  937.     $opt = $tryopt;
  938.     print STDERR ("=> found \"$type\" for ", $opt, "\n") if $debug;
  939.  
  940.     #### Determine argument status ####
  941.  
  942.     # If it is an option w/o argument, we're almost finished with it.
  943.     if ( $type eq '' || $type eq '!' ) {
  944.     if ( defined $optarg ) {
  945.         return 0 if $passthrough;
  946.         print STDERR ("Option ", $opt, " does not take an argument\n");
  947.         $error++;
  948.         undef $opt;
  949.     }
  950.     elsif ( $type eq '' ) {
  951.         $arg = 1;        # supply explicit value
  952.     }
  953.     else {
  954.         substr ($opt, 0, 2) = ''; # strip NO prefix
  955.         $arg = 0;        # supply explicit value
  956.     }
  957.     unshift (@ARGV, $starter.$rest) if defined $rest;
  958.     return 1;
  959.     }
  960.  
  961.     # Get mandatory status and type info.
  962.     my $mand;
  963.     ($mand, $type, $array, $hash) = $type =~ /^(.)(.)(@?)(%?)$/;
  964.  
  965.     # Check if there is an option argument available.
  966.     if ( defined $optarg ? ($optarg eq '') 
  967.      : !(defined $rest || @ARGV > 0) ) {
  968.     # Complain if this option needs an argument.
  969.     if ( $mand eq "=" ) {
  970.         return 0 if $passthrough;
  971.         print STDERR ("Option ", $opt, " requires an argument\n");
  972.         $error++;
  973.         undef $opt;
  974.     }
  975.     if ( $mand eq ":" ) {
  976.         $arg = $type eq "s" ? '' : 0;
  977.     }
  978.     return 1;
  979.     }
  980.  
  981.     # Get (possibly optional) argument.
  982.     $arg = (defined $rest ? $rest
  983.         : (defined $optarg ? $optarg : shift (@ARGV)));
  984.  
  985.     # Get key if this is a "name=value" pair for a hash option.
  986.     $key = undef;
  987.     if ($hash && defined $arg) {
  988.     ($key, $arg) = ($arg =~ /=/o) ? ($`, $') : ($arg, 1);
  989.     }
  990.  
  991.     #### Check if the argument is valid for this option ####
  992.  
  993.     if ( $type eq "s" ) {    # string
  994.     # A mandatory string takes anything. 
  995.     return 1 if $mand eq "=";
  996.  
  997.     # An optional string takes almost anything. 
  998.     return 1 if defined $optarg || defined $rest;
  999.     return 1 if $arg eq "-"; # ??
  1000.  
  1001.     # Check for option or option list terminator.
  1002.     if ($arg eq $argend ||
  1003.         $arg =~ /^$genprefix.+/) {
  1004.         # Push back.
  1005.         unshift (@ARGV, $arg);
  1006.         # Supply empty value.
  1007.         $arg = '';
  1008.     }
  1009.     }
  1010.  
  1011.     elsif ( $type eq "n" || $type eq "i" ) { # numeric/integer
  1012.     if ( $arg !~ /^-?[0-9]+$/ ) {
  1013.         if ( defined $optarg || $mand eq "=" ) {
  1014.         return 0 if $passthrough;
  1015.         print STDERR ("Value \"", $arg, "\" invalid for option ",
  1016.                   $opt, " (number expected)\n");
  1017.         $error++;
  1018.         undef $opt;
  1019.         # Push back.
  1020.         unshift (@ARGV, $starter.$rest) if defined $rest;
  1021.         }
  1022.         else {
  1023.         # Push back.
  1024.         unshift (@ARGV, defined $rest ? $starter.$rest : $arg);
  1025.         # Supply default value.
  1026.         $arg = 0;
  1027.         }
  1028.     }
  1029.     }
  1030.  
  1031.     elsif ( $type eq "f" ) { # real number, int is also ok
  1032.     if ( $arg !~ /^-?[0-9.]+([eE]-?[0-9]+)?$/ ) {
  1033.         if ( defined $optarg || $mand eq "=" ) {
  1034.         return 0 if  $passthrough;
  1035.         print STDERR ("Value \"", $arg, "\" invalid for option ",
  1036.                   $opt, " (real number expected)\n");
  1037.         $error++;
  1038.         undef $opt;
  1039.         # Push back.
  1040.         unshift (@ARGV, $starter.$rest) if defined $rest;
  1041.         }
  1042.         else {
  1043.         # Push back.
  1044.         unshift (@ARGV, defined $rest ? $starter.$rest : $arg);
  1045.         # Supply default value.
  1046.         $arg = 0.0;
  1047.         }
  1048.     }
  1049.     }
  1050.     else {
  1051.     die ("GetOpt::Long internal error (Can't happen)\n");
  1052.     }
  1053.     return 1;
  1054. }
  1055.  
  1056. ################ Package return ################
  1057.  
  1058. 1;
  1059.