1 # GetOpt::Long.pm -- Universal options parsing
5 # RCS Status : $Id: GetoptLong.pm,v 2.11 1997-09-17 12:23:51+02 jv 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 Sep 17 12:20:10 1997
15 GetOptions - extended processing of command line options
20 $result = GetOptions (...option-descriptions...);
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"
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.
39 Command line options can be used to set values. These values can be
40 specified in one of two ways:
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:
52 GetOptions("size=i" => \$offset);
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.
58 Alternatively, the first argument to GetOptions may be a reference to
59 a HASH describing the linkage for the options, or an object whose
60 class is based on a HASH. The following call is equivalent to the
63 %optctl = ("size" => \$offset);
64 GetOptions(\%optctl, "size=i");
66 Linkage may be specified using either of the above methods, or both.
67 Linkage specified in the argument list takes precedence over the
68 linkage specified in the HASH.
70 The command line options are taken from array @ARGV. Upon completion
71 of GetOptions, @ARGV will contain the rest (i.e. the non-options) of
74 Each option specifier designates the name of the option, optionally
75 followed by an argument specifier. Values for argument specifiers are:
81 Option does not take an argument.
82 The option variable will be set to 1.
86 Option does not take an argument and may be negated, i.e. prefixed by
87 "no". E.g. "foo!" will allow B<--foo> (with value 1) and B<-nofoo>
89 The option variable will be set to 1, or 0 if negated.
93 Option takes a mandatory string argument.
94 This string will be assigned to the option variable.
95 Note that even if the string argument starts with B<-> or B<-->, it
96 will not be considered an option on itself.
100 Option takes an optional string argument.
101 This string will be assigned to the option variable.
102 If omitted, it will be assigned "" (an empty string).
103 If the string argument starts with B<-> or B<-->, it
104 will be considered an option on itself.
108 Option takes a mandatory integer argument.
109 This value will be assigned to the option variable.
110 Note that the value may start with B<-> to indicate a negative
115 Option takes an optional integer argument.
116 This value will be assigned to the option variable.
117 If omitted, the value 0 will be assigned.
118 Note that the value may start with B<-> to indicate a negative
123 Option takes a mandatory real number argument.
124 This value will be assigned to the option variable.
125 Note that the value may start with B<-> to indicate a negative
130 Option takes an optional real number argument.
131 This value will be assigned to the option variable.
132 If omitted, the value 0 will be assigned.
136 A lone dash B<-> is considered an option, the corresponding option
137 name is the empty string.
139 A double dash on itself B<--> signals end of the options list.
141 =head2 Linkage specification
143 The linkage specifier is optional. If no linkage is explicitly
144 specified but a ref HASH is passed, GetOptions will place the value in
145 the HASH. For example:
148 GetOptions (\%optctl, "size=i");
150 will perform the equivalent of the assignment
152 $optctl{"size"} = 24;
154 For array options, a reference to an array is used, e.g.:
157 GetOptions (\%optctl, "sizes=i@");
159 with command line "-sizes 24 -sizes 48" will perform the equivalent of
162 $optctl{"sizes"} = [24, 48];
164 For hash options (an option whose argument looks like "name=value"),
165 a reference to a hash is used, e.g.:
168 GetOptions (\%optctl, "define=s%");
170 with command line "--define foo=hello --define bar=world" will perform the
171 equivalent of the assignment
173 $optctl{"define"} = {foo=>'hello', bar=>'world')
175 If no linkage is explicitly specified and no ref HASH is passed,
176 GetOptions will put the value in a global variable named after the
177 option, prefixed by "opt_". To yield a usable Perl variable,
178 characters that are not part of the syntax for variables are
179 translated to underscores. For example, "--fpp-struct-return" will set
180 the variable $opt_fpp_struct_return. Note that this variable resides
181 in the namespace of the calling program, not necessarily B<main>.
184 GetOptions ("size=i", "sizes=i@");
186 with command line "-size 10 -sizes 24 -sizes 48" will perform the
187 equivalent of the assignments
190 @opt_sizes = (24, 48);
192 A lone dash B<-> is considered an option, the corresponding Perl
193 identifier is $opt_ .
195 The linkage specifier can be a reference to a scalar, a reference to
196 an array, a reference to a hash or a reference to a subroutine.
198 If a REF SCALAR is supplied, the new value is stored in the referenced
199 variable. If the option occurs more than once, the previous value is
202 If a REF ARRAY is supplied, the new value is appended (pushed) to the
205 If a REF HASH is supplied, the option value should look like "key" or
206 "key=value" (if the "=value" is omitted then a value of 1 is implied).
207 In this case, the element of the referenced hash with the key "key"
210 If a REF CODE is supplied, the referenced subroutine is called with
211 two arguments: the option name and the option value.
212 The option name is always the true name, not an abbreviation or alias.
214 =head2 Aliases and abbreviations
216 The option name may actually be a list of option names, separated by
217 "|"s, e.g. "foo|bar|blech=s". In this example, "foo" is the true name
218 of this option. If no linkage is specified, options "foo", "bar" and
219 "blech" all will set $opt_foo.
221 Option names may be abbreviated to uniqueness, depending on
222 configuration option B<auto_abbrev>.
224 =head2 Non-option call-back routine
226 A special option specifier, E<lt>E<gt>, can be used to designate a subroutine
227 to handle non-option arguments. GetOptions will immediately call this
228 subroutine for every non-option it encounters in the options list.
229 This subroutine gets the name of the non-option passed.
230 This feature requires configuration option B<permute>, see section
231 CONFIGURATION OPTIONS.
233 See also the examples.
235 =head2 Option starters
237 On the command line, options can start with B<-> (traditional), B<-->
238 (POSIX) and B<+> (GNU, now being phased out). The latter is not
239 allowed if the environment variable B<POSIXLY_CORRECT> has been
242 Options that start with "--" may have an argument appended, separated
243 with an "=", e.g. "--foo=bar".
247 A return status of 0 (false) indicates that the function detected
252 Getopt::Long::GetOptions() is the successor of
253 B<newgetopt.pl> that came with Perl 4. It is fully upward compatible.
254 In fact, the Perl 5 version of newgetopt.pl is just a wrapper around
257 If an "@" sign is appended to the argument specifier, the option is
258 treated as an array. Value(s) are not set, but pushed into array
259 @opt_name. If explicit linkage is supplied, this must be a reference
262 If an "%" sign is appended to the argument specifier, the option is
263 treated as a hash. Value(s) of the form "name=value" are set by
264 setting the element of the hash %opt_name with key "name" to "value"
265 (if the "=value" portion is omitted it defaults to 1). If explicit
266 linkage is supplied, this must be a reference to a HASH.
268 If configuration option B<getopt_compat> is set (see section
269 CONFIGURATION OPTIONS), options that start with "+" or "-" may also
270 include their arguments, e.g. "+foo=bar". This is for compatiblity
271 with older implementations of the GNU "getopt" routine.
273 If the first argument to GetOptions is a string consisting of only
274 non-alphanumeric characters, it is taken to specify the option starter
275 characters. Everything starting with one of these characters from the
276 starter will be considered an option. B<Using a starter argument is
277 strongly deprecated.>
279 For convenience, option specifiers may have a leading B<-> or B<-->,
280 so it is possible to write:
282 GetOptions qw(-foo=s --bar=i --ar=s);
286 If the option specifier is "one:i" (i.e. takes an optional integer
287 argument), then the following situations are handled:
289 -one -two -> $opt_one = '', -two is next option
290 -one -2 -> $opt_one = -2
292 Also, assume specifiers "foo=s" and "bar:s" :
294 -bar -xxx -> $opt_bar = '', '-xxx' is next option
295 -foo -bar -> $opt_foo = '-bar'
296 -foo -- -> $opt_foo = '--'
298 In GNU or POSIX format, option names and values can be combined:
300 +foo=blech -> $opt_foo = 'blech'
301 --bar= -> $opt_bar = ''
302 --bar=-- -> $opt_bar = '--'
304 Example of using variable references:
306 $ret = GetOptions ('foo=s', \$foo, 'bar=i', 'ar=s', \@ar);
308 With command line options "-foo blech -bar 24 -ar xx -ar yy"
315 Example of using the E<lt>E<gt> option specifier:
317 @ARGV = qw(-foo 1 bar -foo 2 blech);
318 GetOptions("foo=i", \$myfoo, "<>", \&mysub);
322 mysub("bar") will be called (with $myfoo being 1)
323 mysub("blech") will be called (with $myfoo being 2)
327 @ARGV = qw(-foo 1 bar -foo 2 blech);
328 GetOptions("foo=i", \$myfoo);
330 This will leave the non-options in @ARGV:
333 @ARGV -> qw(bar blech)
335 =head1 CONFIGURATION OPTIONS
337 B<GetOptions> can be configured by calling subroutine
338 B<Getopt::Long::config>. This subroutine takes a list of quoted
339 strings, each specifying a configuration option to be set, e.g.
340 B<ignore_case>. Options can be reset by prefixing with B<no_>, e.g.
341 B<no_ignore_case>. Case does not matter. Multiple calls to B<config>
344 Previous versions of Getopt::Long used variables for the purpose of
345 configuring. Although manipulating these variables still work, it
346 is strongly encouraged to use the new B<config> routine. Besides, it
349 The following options are available:
355 This option causes all configuration options to be reset to their
360 Allow option names to be abbreviated to uniqueness.
361 Default is set unless environment variable
362 POSIXLY_CORRECT has been set, in which case B<auto_abbrev> is reset.
366 Allow '+' to start options.
367 Default is set unless environment variable
368 POSIXLY_CORRECT has been set, in which case B<getopt_compat> is reset.
372 Whether non-options are allowed to be mixed with
374 Default is set unless environment variable
375 POSIXLY_CORRECT has been set, in which case b<require_order> is reset.
377 See also B<permute>, which is the opposite of B<require_order>.
381 Whether non-options are allowed to be mixed with
383 Default is set unless environment variable
384 POSIXLY_CORRECT has been set, in which case B<permute> is reset.
385 Note that B<permute> is the opposite of B<require_order>.
387 If B<permute> is set, this means that
389 -foo arg1 -bar arg2 arg3
393 -foo -bar arg1 arg2 arg3
395 If a non-option call-back routine is specified, @ARGV will always be
396 empty upon succesful return of GetOptions since all options have been
397 processed, except when B<--> is used:
399 -foo arg1 -bar arg2 -- arg3
401 will call the call-back routine for arg1 and arg2, and terminate
402 leaving arg2 in @ARGV.
404 If B<require_order> is set, options processing
405 terminates when the first non-option is encountered.
407 -foo arg1 -bar arg2 arg3
411 -foo -- arg1 -bar arg2 arg3
413 =item bundling (default: reset)
415 Setting this variable to a non-zero value will allow single-character
416 options to be bundled. To distinguish bundles from long option names,
417 long options must be introduced with B<--> and single-character
418 options (and bundles) with B<->. For example,
422 would be equivalent to
426 provided "vax", "v", "a" and "x" have been defined to be valid
429 Bundled options can also include a value in the bundle; this value has
430 to be the last part of the bundle, e.g.
438 Note: resetting B<bundling> also resets B<bundling_override>.
440 =item bundling_override (default: reset)
442 If B<bundling_override> is set, bundling is enabled as with
443 B<bundling> but now long option names override option bundles. In the
444 above example, B<-vax> would be interpreted as the option "vax", not
445 the bundle "v", "a", "x".
447 Note: resetting B<bundling_override> also resets B<bundling>.
449 B<Note:> Using option bundling can easily lead to unexpected results,
450 especially when mixing long options and bundles. Caveat emptor.
452 =item ignore_case (default: set)
454 If set, case is ignored when matching options.
456 Note: resetting B<ignore_case> also resets B<ignore_case_always>.
458 =item ignore_case_always (default: reset)
460 When bundling is in effect, case is ignored on single-character
463 Note: resetting B<ignore_case_always> also resets B<ignore_case>.
465 =item pass_through (default: reset)
467 Unknown options are passed through in @ARGV instead of being flagged
468 as errors. This makes it possible to write wrapper scripts that
469 process only part of the user supplied options, and passes the
470 remaining options to some other program.
472 This can be very confusing, especially when B<permute> is also set.
474 =item debug (default: reset)
476 Enable copious debugging output.
480 =head1 OTHER USEFUL VARIABLES
484 =item $Getopt::Long::VERSION
486 The version number of this Getopt::Long implementation in the format
487 C<major>.C<minor>. This can be used to have Exporter check the
490 use Getopt::Long 3.00;
492 You can inspect $Getopt::Long::major_version and
493 $Getopt::Long::minor_version for the individual components.
495 =item $Getopt::Long::error
497 Internal error flag. May be incremented from a call-back routine to
498 cause options parsing to fail.
504 ################ Copyright ################
506 # This program is Copyright 1990,1997 by Johan Vromans.
507 # This program is free software; you can redistribute it and/or
508 # modify it under the terms of the GNU General Public License
509 # as published by the Free Software Foundation; either version 2
510 # of the License, or (at your option) any later version.
512 # This program is distributed in the hope that it will be useful,
513 # but WITHOUT ANY WARRANTY; without even the implied warranty of
514 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
515 # GNU General Public License for more details.
517 # If you do not have a copy of the GNU General Public License write to
518 # the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
521 ################ Module Preamble ################
528 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
529 $VERSION = sprintf("%d.%02d", q$Revision: 2.11 $ =~ /(\d+)\.(\d+)/);
532 @EXPORT = qw(&GetOptions $REQUIRE_ORDER $PERMUTE $RETURN_IN_ORDER);
537 use vars @EXPORT, @EXPORT_OK;
538 # User visible variables.
539 use vars qw($error $debug $major_version $minor_version);
540 # Deprecated visible variables.
541 use vars qw($autoabbrev $getopt_compat $ignorecase $bundling $order
544 ################ Local Variables ################
546 my $gen_prefix; # generic prefix (option starters)
547 my $argend; # option list terminator
548 my %opctl; # table of arg.specs (long and abbrevs)
549 my %bopctl; # table of arg.specs (bundles)
550 my @opctl; # the possible long option names
551 my $pkg; # current context. Needed if no linkage.
552 my %aliases; # alias table
553 my $genprefix; # so we can call the same module more
554 my $opt; # current option
555 my $arg; # current option value, if any
556 my $array; # current option is array typed
557 my $hash; # current option is hash typed
558 my $key; # hash key for a hash option
559 # than once in differing environments
560 my $config_defaults; # set config defaults
561 my $find_option; # helper routine
563 ################ Subroutines ################
567 my @optionlist = @_; # local copy of the option descriptions
568 $argend = '--'; # option list terminator
569 %opctl = (); # table of arg.specs (long and abbrevs)
570 %bopctl = (); # table of arg.specs (bundles)
571 $pkg = (caller)[0]; # current context
572 # Needed if linkage is omitted.
573 %aliases= (); # alias table
574 my @ret = (); # accum for non-options
575 my %linkage; # linkage
576 my $userlinkage; # user supplied HASH
577 $genprefix = $gen_prefix; # so we can call the same module many times
580 print STDERR ('GetOptions $Revision: 2.11 $ ',
581 "[GetOpt::Long $Getopt::Long::VERSION] -- ",
582 "called from package \"$pkg\".\n",
584 " autoabbrev=$autoabbrev".
585 ",bundling=$bundling",
586 ",getopt_compat=$getopt_compat",
588 ",\n ignorecase=$ignorecase",
589 ",passthrough=$passthrough",
590 ",genprefix=\"$genprefix\"",
594 # Check for ref HASH as first argument.
595 # First argument may be an object. It's OK to use this as long
596 # as it is really a hash underneath.
597 $userlinkage = undef;
598 if ( ref($optionlist[0]) and
599 "$optionlist[0]" =~ /^(?:.*\=)?HASH\([^\(]*\)$/ ) {
600 $userlinkage = shift (@optionlist);
601 print STDERR ("=> user linkage: $userlinkage\n") if $debug;
604 # See if the first element of the optionlist contains option
605 # starter characters.
606 if ( $optionlist[0] =~ /^\W+$/ ) {
607 $genprefix = shift (@optionlist);
609 $genprefix =~ s/(\W)/\\$1/g;
610 $genprefix = "[" . $genprefix . "]";
613 # Verify correctness of optionlist.
616 while ( @optionlist > 0 ) {
617 my $opt = shift (@optionlist);
619 # Strip leading prefix so people can specify "--foo=i" if they like.
620 $opt = $' if $opt =~ /^($genprefix)+/;
622 if ( $opt eq '<>' ) {
623 if ( (defined $userlinkage)
624 && !(@optionlist > 0 && ref($optionlist[0]))
625 && (exists $userlinkage->{$opt})
626 && ref($userlinkage->{$opt}) ) {
627 unshift (@optionlist, $userlinkage->{$opt});
629 unless ( @optionlist > 0
630 && ref($optionlist[0]) && ref($optionlist[0]) eq 'CODE' ) {
631 warn ("Option spec <> requires a reference to a subroutine\n");
635 $linkage{'<>'} = shift (@optionlist);
639 if ( $opt !~ /^(\w+[-\w|]*)?(!|[=:][infse][@%]?)?$/ ) {
640 warn ("Error in option spec: \"", $opt, "\"\n");
644 my ($o, $c, $a) = ($1, $2);
645 $c = '' unless defined $c;
647 if ( ! defined $o ) {
648 # empty -> '-' option
649 $opctl{$o = ''} = $c;
653 my @o = split (/\|/, $o);
654 my $linko = $o = $o[0];
655 # Force an alias if the option name is not locase.
656 $a = $o unless $o eq lc($o);
660 && ($bundling ? length($o) > 1 : 1));
663 if ( $bundling && length($_) == 1 ) {
664 $_ = lc ($_) if $ignorecase > 1;
667 warn ("Ignoring '!' modifier for short option $_\n");
670 $opctl{$_} = $bopctl{$_} = $c;
673 $_ = lc ($_) if $ignorecase;
692 # If no linkage is supplied in the @optionlist, copy it from
693 # the userlinkage if available.
694 if ( defined $userlinkage ) {
695 unless ( @optionlist > 0 && ref($optionlist[0]) ) {
696 if ( exists $userlinkage->{$o} && ref($userlinkage->{$o}) ) {
697 print STDERR ("=> found userlinkage for \"$o\": ",
698 "$userlinkage->{$o}\n")
700 unshift (@optionlist, $userlinkage->{$o});
703 # Do nothing. Being undefined will be handled later.
709 # Copy the linkage. If omitted, link to global variable.
710 if ( @optionlist > 0 && ref($optionlist[0]) ) {
711 print STDERR ("=> link \"$o\" to $optionlist[0]\n")
713 if ( ref($optionlist[0]) =~ /^(SCALAR|CODE)$/ ) {
714 $linkage{$o} = shift (@optionlist);
716 elsif ( ref($optionlist[0]) =~ /^(ARRAY)$/ ) {
717 $linkage{$o} = shift (@optionlist);
719 if $opctl{$o} ne '' and $opctl{$o} !~ /\@$/;
721 if $bundling and $bopctl{$o} ne '' and $bopctl{$o} !~ /\@$/;
723 elsif ( ref($optionlist[0]) =~ /^(HASH)$/ ) {
724 $linkage{$o} = shift (@optionlist);
726 if $opctl{$o} ne '' and $opctl{$o} !~ /\%$/;
728 if $bundling and $bopctl{$o} ne '' and $bopctl{$o} !~ /\%$/;
731 warn ("Invalid option linkage for \"", $opt, "\"\n");
736 # Link to global $opt_XXX variable.
737 # Make sure a valid perl identifier results.
741 print STDERR ("=> link \"$o\" to \@$pkg","::opt_$ov\n")
743 eval ("\$linkage{\$o} = \\\@".$pkg."::opt_$ov;");
745 elsif ( $c =~ /%/ ) {
746 print STDERR ("=> link \"$o\" to \%$pkg","::opt_$ov\n")
748 eval ("\$linkage{\$o} = \\\%".$pkg."::opt_$ov;");
751 print STDERR ("=> link \"$o\" to \$$pkg","::opt_$ov\n")
753 eval ("\$linkage{\$o} = \\\$".$pkg."::opt_$ov;");
758 # Bail out if errors found.
761 # Sort the possible long option names.
762 @opctl = sort(keys (%opctl)) if $autoabbrev;
764 # Show the options tables if debugging.
768 while ( ($k,$v) = each(%opctl) ) {
769 print STDERR ($arrow, "\$opctl{\"$k\"} = \"$v\"\n");
773 while ( ($k,$v) = each(%bopctl) ) {
774 print STDERR ($arrow, "\$bopctl{\"$k\"} = \"$v\"\n");
779 # Process argument list
780 while ( @ARGV > 0 ) {
782 #### Get next argument ####
784 $opt = shift (@ARGV);
787 print STDERR ("=> option \"", $opt, "\"\n") if $debug;
789 #### Determine what we have ####
791 # Double dash is option list terminator.
792 if ( $opt eq $argend ) {
793 # Finish. Push back accumulated arguments and return.
794 unshift (@ARGV, @ret)
795 if $order == $PERMUTE;
796 return ($error == 0);
801 # find_option operates on the GLOBAL $opt and $arg!
802 if ( &$find_option () ) {
804 # find_option undefines $opt in case of errors.
805 next unless defined $opt;
807 if ( defined $arg ) {
808 $opt = $aliases{$opt} if defined $aliases{$opt};
810 if ( defined $linkage{$opt} ) {
811 print STDERR ("=> ref(\$L{$opt}) -> ",
812 ref($linkage{$opt}), "\n") if $debug;
814 if ( ref($linkage{$opt}) eq 'SCALAR' ) {
815 print STDERR ("=> \$\$L{$opt} = \"$arg\"\n") if $debug;
816 ${$linkage{$opt}} = $arg;
818 elsif ( ref($linkage{$opt}) eq 'ARRAY' ) {
819 print STDERR ("=> push(\@{\$L{$opt}, \"$arg\")\n")
821 push (@{$linkage{$opt}}, $arg);
823 elsif ( ref($linkage{$opt}) eq 'HASH' ) {
824 print STDERR ("=> \$\$L{$opt}->{$key} = \"$arg\"\n")
826 $linkage{$opt}->{$key} = $arg;
828 elsif ( ref($linkage{$opt}) eq 'CODE' ) {
829 print STDERR ("=> &L{$opt}(\"$opt\", \"$arg\")\n")
831 &{$linkage{$opt}}($opt, $arg);
834 print STDERR ("Invalid REF type \"", ref($linkage{$opt}),
836 die ("Getopt::Long -- internal error!\n");
839 # No entry in linkage means entry in userlinkage.
841 if ( defined $userlinkage->{$opt} ) {
842 print STDERR ("=> push(\@{\$L{$opt}}, \"$arg\")\n")
844 push (@{$userlinkage->{$opt}}, $arg);
847 print STDERR ("=>\$L{$opt} = [\"$arg\"]\n")
849 $userlinkage->{$opt} = [$arg];
853 if ( defined $userlinkage->{$opt} ) {
854 print STDERR ("=> \$L{$opt}->{$key} = \"$arg\"\n")
856 $userlinkage->{$opt}->{$key} = $arg;
859 print STDERR ("=>\$L{$opt} = {$key => \"$arg\"}\n")
861 $userlinkage->{$opt} = {$key => $arg};
865 print STDERR ("=>\$L{$opt} = \"$arg\"\n") if $debug;
866 $userlinkage->{$opt} = $arg;
871 # Not an option. Save it if we $PERMUTE and don't have a <>.
872 elsif ( $order == $PERMUTE ) {
873 # Try non-options call-back.
875 if ( (defined ($cb = $linkage{'<>'})) ) {
879 print STDERR ("=> saving \"$tryopt\" ",
880 "(not an option, may permute)\n") if $debug;
881 push (@ret, $tryopt);
886 # ...otherwise, terminate.
888 # Push this one back and exit.
889 unshift (@ARGV, $tryopt);
890 return ($error == 0);
896 if ( $order == $PERMUTE ) {
897 # Push back accumulated arguments
898 print STDERR ("=> restoring \"", join('" "', @ret), "\"\n")
899 if $debug && @ret > 0;
900 unshift (@ARGV, @ret) if @ret > 0;
903 return ($error == 0);
909 foreach $opt ( @options ) {
912 if ( $try =~ /^no_?/ ) {
916 if ( $try eq 'default' or $try eq 'defaults' ) {
917 &$config_defaults () if $action;
919 elsif ( $try eq 'auto_abbrev' or $try eq 'autoabbrev' ) {
920 $autoabbrev = $action;
922 elsif ( $try eq 'getopt_compat' ) {
923 $getopt_compat = $action;
925 elsif ( $try eq 'ignorecase' or $try eq 'ignore_case' ) {
926 $ignorecase = $action;
928 elsif ( $try eq 'ignore_case_always' ) {
929 $ignorecase = $action ? 2 : 0;
931 elsif ( $try eq 'bundling' ) {
934 elsif ( $try eq 'bundling_override' ) {
935 $bundling = $action ? 2 : 0;
937 elsif ( $try eq 'require_order' ) {
938 $order = $action ? $REQUIRE_ORDER : $PERMUTE;
940 elsif ( $try eq 'permute' ) {
941 $order = $action ? $PERMUTE : $REQUIRE_ORDER;
943 elsif ( $try eq 'pass_through' or $try eq 'passthrough' ) {
944 $passthrough = $action;
946 elsif ( $try eq 'debug' ) {
950 $Carp::CarpLevel = 1;
951 Carp::croak("Getopt::Long: unknown config parameter \"$opt\"")
956 # Modified from Exporter. This one handles 2.001 and 2.01 etc just like 2.1.
957 sub require_version {
959 my ($self, $wanted) = @_;
960 my $pkg = ref $self || $self;
961 my $version = $ {"${pkg}::VERSION"} || "(undef)";
963 $wanted .= '.0' unless $wanted =~ /\./;
964 $wanted = $1 * 1000 + $2 if $wanted =~ /^(\d+)\.(\d+)$/;
965 $version = $1 * 1000 + $2 if $version =~ /^(\d+)\.(\d+)$/;
966 if ( $version < $wanted ) {
967 $version =~ s/^(\d+)(\d\d\d)$/$1.'.'.(0+$2)/e;
968 $wanted =~ s/^(\d+)(\d\d\d)$/$1.'.'.(0+$2)/e;
969 $Carp::CarpLevel = 1;
970 Carp::croak("$pkg $wanted required--this is only version $version")
975 ################ Private Subroutines ################
979 return 0 unless $opt =~ /^$genprefix/;
984 my $optarg = undef; # value supplied with --opt=value
985 my $rest = undef; # remainder from unbundling
987 # If it is a long option, it may include the value.
988 if (($starter eq "--" || $getopt_compat)
989 && $opt =~ /^([^=]+)=/ ) {
992 print STDERR ("=> option \"", $opt,
993 "\", optarg = \"$optarg\"\n") if $debug;
998 my $tryopt = $opt; # option to try
999 my $optbl = \%opctl; # table to look it up (long names)
1002 if ( $bundling && $starter eq '-' ) {
1003 # Unbundle single letter option.
1004 $rest = substr ($tryopt, 1);
1005 $tryopt = substr ($tryopt, 0, 1);
1006 $tryopt = lc ($tryopt) if $ignorecase > 1;
1007 print STDERR ("=> $starter$tryopt unbundled from ",
1008 "$starter$tryopt$rest\n") if $debug;
1009 $rest = undef unless $rest ne '';
1010 $optbl = \%bopctl; # look it up in the short names table
1012 # If bundling == 2, long options can override bundles.
1013 if ( $bundling == 2 and
1014 defined ($type = $opctl{$tryopt.$rest}) ) {
1015 print STDERR ("=> $starter$tryopt rebundled to ",
1016 "$starter$tryopt$rest\n") if $debug;
1022 # Try auto-abbreviation.
1023 elsif ( $autoabbrev ) {
1024 # Downcase if allowed.
1025 $tryopt = $opt = lc ($opt) if $ignorecase;
1026 # Turn option name into pattern.
1027 my $pat = quotemeta ($opt);
1028 # Look up in option names.
1029 my @hits = grep (/^$pat/, @opctl);
1030 print STDERR ("=> ", scalar(@hits), " hits (@hits) with \"$pat\" ",
1031 "out of ", scalar(@opctl), "\n") if $debug;
1033 # Check for ambiguous results.
1034 unless ( (@hits <= 1) || (grep ($_ eq $opt, @hits) == 1) ) {
1035 # See if all matches are for the same option.
1038 $_ = $aliases{$_} if defined $aliases{$_};
1041 # Now see if it really is ambiguous.
1042 unless ( keys(%hit) == 1 ) {
1043 return 0 if $passthrough;
1044 print STDERR ("Option ", $opt, " is ambiguous (",
1045 join(", ", @hits), ")\n");
1053 # Complete the option name, if appropriate.
1054 if ( @hits == 1 && $hits[0] ne $opt ) {
1056 $tryopt = lc ($tryopt) if $ignorecase;
1057 print STDERR ("=> option \"$opt\" -> \"$tryopt\"\n")
1062 # Map to all lowercase if ignoring case.
1063 elsif ( $ignorecase ) {
1064 $tryopt = lc ($opt);
1067 # Check validity by fetching the info.
1068 $type = $optbl->{$tryopt} unless defined $type;
1069 unless ( defined $type ) {
1070 return 0 if $passthrough;
1071 warn ("Unknown option: ", $opt, "\n");
1077 print STDERR ("=> found \"$type\" for ", $opt, "\n") if $debug;
1079 #### Determine argument status ####
1081 # If it is an option w/o argument, we're almost finished with it.
1082 if ( $type eq '' || $type eq '!' ) {
1083 if ( defined $optarg ) {
1084 return 0 if $passthrough;
1085 print STDERR ("Option ", $opt, " does not take an argument\n");
1089 elsif ( $type eq '' ) {
1090 $arg = 1; # supply explicit value
1093 substr ($opt, 0, 2) = ''; # strip NO prefix
1094 $arg = 0; # supply explicit value
1096 unshift (@ARGV, $starter.$rest) if defined $rest;
1100 # Get mandatory status and type info.
1102 ($mand, $type, $array, $hash) = $type =~ /^(.)(.)(@?)(%?)$/;
1104 # Check if there is an option argument available.
1105 if ( defined $optarg ? ($optarg eq '')
1106 : !(defined $rest || @ARGV > 0) ) {
1107 # Complain if this option needs an argument.
1108 if ( $mand eq "=" ) {
1109 return 0 if $passthrough;
1110 print STDERR ("Option ", $opt, " requires an argument\n");
1114 if ( $mand eq ":" ) {
1115 $arg = $type eq "s" ? '' : 0;
1120 # Get (possibly optional) argument.
1121 $arg = (defined $rest ? $rest
1122 : (defined $optarg ? $optarg : shift (@ARGV)));
1124 # Get key if this is a "name=value" pair for a hash option.
1126 if ($hash && defined $arg) {
1127 ($key, $arg) = ($arg =~ /=/o) ? ($`, $') : ($arg, 1);
1130 #### Check if the argument is valid for this option ####
1132 if ( $type eq "s" ) { # string
1133 # A mandatory string takes anything.
1134 return 1 if $mand eq "=";
1136 # An optional string takes almost anything.
1137 return 1 if defined $optarg || defined $rest;
1138 return 1 if $arg eq "-"; # ??
1140 # Check for option or option list terminator.
1141 if ($arg eq $argend ||
1142 $arg =~ /^$genprefix.+/) {
1144 unshift (@ARGV, $arg);
1145 # Supply empty value.
1150 elsif ( $type eq "n" || $type eq "i" ) { # numeric/integer
1151 if ( $arg !~ /^-?[0-9]+$/ ) {
1152 if ( defined $optarg || $mand eq "=" ) {
1153 if ( $passthrough ) {
1154 unshift (@ARGV, defined $rest ? $starter.$rest : $arg)
1155 unless defined $optarg;
1158 print STDERR ("Value \"", $arg, "\" invalid for option ",
1159 $opt, " (number expected)\n");
1163 unshift (@ARGV, $starter.$rest) if defined $rest;
1167 unshift (@ARGV, defined $rest ? $starter.$rest : $arg);
1168 # Supply default value.
1174 elsif ( $type eq "f" ) { # real number, int is also ok
1175 if ( $arg !~ /^-?[0-9.]+([eE]-?[0-9]+)?$/ ) {
1176 if ( defined $optarg || $mand eq "=" ) {
1177 if ( $passthrough ) {
1178 unshift (@ARGV, defined $rest ? $starter.$rest : $arg)
1179 unless defined $optarg;
1182 print STDERR ("Value \"", $arg, "\" invalid for option ",
1183 $opt, " (real number expected)\n");
1187 unshift (@ARGV, $starter.$rest) if defined $rest;
1191 unshift (@ARGV, defined $rest ? $starter.$rest : $arg);
1192 # Supply default value.
1198 die ("GetOpt::Long internal error (Can't happen)\n");
1203 $config_defaults = sub {
1204 # Handle POSIX compliancy.
1205 if ( defined $ENV{"POSIXLY_CORRECT"} ) {
1206 $gen_prefix = "(--|-)";
1207 $autoabbrev = 0; # no automatic abbrev of options
1208 $bundling = 0; # no bundling of single letter switches
1209 $getopt_compat = 0; # disallow '+' to start options
1210 $order = $REQUIRE_ORDER;
1213 $gen_prefix = "(--|-|\\+)";
1214 $autoabbrev = 1; # automatic abbrev of options
1215 $bundling = 0; # bundling off by default
1216 $getopt_compat = 1; # allow '+' to start options
1219 # Other configurable settings.
1220 $debug = 0; # for debugging
1221 $error = 0; # error tally
1222 $ignorecase = 1; # ignore case when matching options
1223 $passthrough = 0; # leave unrecognized options alone
1226 ################ Initialization ################
1228 # Values for $order. See GNU getopt.c for details.
1229 ($REQUIRE_ORDER, $PERMUTE, $RETURN_IN_ORDER) = (0..2);
1230 # Version major/minor numbers.
1231 ($major_version, $minor_version) = $VERSION =~ /^(\d+)\.(\d+)/;
1234 &$config_defaults ();
1236 ################ Package return ################