home *** CD-ROM | disk | FTP | other *** search
/ CLIX - Fazer Clix Custa Nix / CLIX-CD.cdr / mac / lib / Getopt / Long.pm next >
Text File  |  1997-05-19  |  35KB  |  1,226 lines

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