1 # GetOpt::Long.pm -- Universal options parsing
5 # RCS Status : $Id: GetoptLong.pm,v 2.13 1997-12-25 16:20:17+01 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: Thu Dec 25 16:18:08 1997
13 ################ Copyright ################
15 # This program is Copyright 1990,1997 by Johan Vromans.
16 # This program is free software; you can redistribute it and/or
17 # modify it under the terms of the GNU General Public License
18 # as published by the Free Software Foundation; either version 2
19 # of the License, or (at your option) any later version.
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 # GNU General Public License for more details.
26 # If you do not have a copy of the GNU General Public License write to
27 # the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
30 ################ Module Preamble ################
37 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
38 $VERSION = sprintf("%d.%02d", q$Revision: 2.13 $ =~ /(\d+)\.(\d+)/);
41 @EXPORT = qw(&GetOptions $REQUIRE_ORDER $PERMUTE $RETURN_IN_ORDER);
46 use vars @EXPORT, @EXPORT_OK;
47 # User visible variables.
48 use vars qw($error $debug $major_version $minor_version);
49 # Deprecated visible variables.
50 use vars qw($autoabbrev $getopt_compat $ignorecase $bundling $order
53 ################ Local Variables ################
55 my $gen_prefix; # generic prefix (option starters)
56 my $argend; # option list terminator
57 my %opctl; # table of arg.specs (long and abbrevs)
58 my %bopctl; # table of arg.specs (bundles)
59 my @opctl; # the possible long option names
60 my $pkg; # current context. Needed if no linkage.
61 my %aliases; # alias table
62 my $genprefix; # so we can call the same module more
63 my $opt; # current option
64 my $arg; # current option value, if any
65 my $array; # current option is array typed
66 my $hash; # current option is hash typed
67 my $key; # hash key for a hash option
68 # than once in differing environments
69 my $config_defaults; # set config defaults
70 my $find_option; # helper routine
71 my $croak; # helper routine
73 ################ Subroutines ################
77 my @optionlist = @_; # local copy of the option descriptions
78 $argend = '--'; # option list terminator
79 %opctl = (); # table of arg.specs (long and abbrevs)
80 %bopctl = (); # table of arg.specs (bundles)
81 $pkg = (caller)[0]; # current context
82 # Needed if linkage is omitted.
83 %aliases= (); # alias table
84 my @ret = (); # accum for non-options
85 my %linkage; # linkage
86 my $userlinkage; # user supplied HASH
87 $genprefix = $gen_prefix; # so we can call the same module many times
90 print STDERR ('GetOptions $Revision: 2.13 $ ',
91 "[GetOpt::Long $Getopt::Long::VERSION] -- ",
92 "called from package \"$pkg\".\n",
94 " autoabbrev=$autoabbrev".
95 ",bundling=$bundling",
96 ",getopt_compat=$getopt_compat",
98 ",\n ignorecase=$ignorecase",
99 ",passthrough=$passthrough",
100 ",genprefix=\"$genprefix\"",
104 # Check for ref HASH as first argument.
105 # First argument may be an object. It's OK to use this as long
106 # as it is really a hash underneath.
107 $userlinkage = undef;
108 if ( ref($optionlist[0]) and
109 "$optionlist[0]" =~ /^(?:.*\=)?HASH\([^\(]*\)$/ ) {
110 $userlinkage = shift (@optionlist);
111 print STDERR ("=> user linkage: $userlinkage\n") if $debug;
114 # See if the first element of the optionlist contains option
115 # starter characters.
116 if ( $optionlist[0] =~ /^\W+$/ ) {
117 $genprefix = shift (@optionlist);
118 # Turn into regexp. Needs to be parenthesized!
119 $genprefix =~ s/(\W)/\\$1/g;
120 $genprefix = "([" . $genprefix . "])";
123 # Verify correctness of optionlist.
126 while ( @optionlist > 0 ) {
127 my $opt = shift (@optionlist);
129 # Strip leading prefix so people can specify "--foo=i" if they like.
130 $opt = $2 if $opt =~ /^$genprefix+(.*)$/;
132 if ( $opt eq '<>' ) {
133 if ( (defined $userlinkage)
134 && !(@optionlist > 0 && ref($optionlist[0]))
135 && (exists $userlinkage->{$opt})
136 && ref($userlinkage->{$opt}) ) {
137 unshift (@optionlist, $userlinkage->{$opt});
139 unless ( @optionlist > 0
140 && ref($optionlist[0]) && ref($optionlist[0]) eq 'CODE' ) {
141 $error .= "Option spec <> requires a reference to a subroutine\n";
144 $linkage{'<>'} = shift (@optionlist);
148 # Match option spec. Allow '?' as an alias.
149 if ( $opt !~ /^((\w+[-\w]*)(\|(\?|\w[-\w]*)?)*)?(!|[=:][infse][@%]?)?$/ ) {
150 $error .= "Error in option spec: \"$opt\"\n";
153 my ($o, $c, $a) = ($1, $5);
154 $c = '' unless defined $c;
156 if ( ! defined $o ) {
157 # empty -> '-' option
158 $opctl{$o = ''} = $c;
162 my @o = split (/\|/, $o);
163 my $linko = $o = $o[0];
164 # Force an alias if the option name is not locase.
165 $a = $o unless $o eq lc($o);
169 && ($bundling ? length($o) > 1 : 1));
172 if ( $bundling && length($_) == 1 ) {
173 $_ = lc ($_) if $ignorecase > 1;
176 warn ("Ignoring '!' modifier for short option $_\n");
179 $opctl{$_} = $bopctl{$_} = $c;
182 $_ = lc ($_) if $ignorecase;
201 # If no linkage is supplied in the @optionlist, copy it from
202 # the userlinkage if available.
203 if ( defined $userlinkage ) {
204 unless ( @optionlist > 0 && ref($optionlist[0]) ) {
205 if ( exists $userlinkage->{$o} && ref($userlinkage->{$o}) ) {
206 print STDERR ("=> found userlinkage for \"$o\": ",
207 "$userlinkage->{$o}\n")
209 unshift (@optionlist, $userlinkage->{$o});
212 # Do nothing. Being undefined will be handled later.
218 # Copy the linkage. If omitted, link to global variable.
219 if ( @optionlist > 0 && ref($optionlist[0]) ) {
220 print STDERR ("=> link \"$o\" to $optionlist[0]\n")
222 if ( ref($optionlist[0]) =~ /^(SCALAR|CODE)$/ ) {
223 $linkage{$o} = shift (@optionlist);
225 elsif ( ref($optionlist[0]) =~ /^(ARRAY)$/ ) {
226 $linkage{$o} = shift (@optionlist);
228 if $opctl{$o} ne '' and $opctl{$o} !~ /\@$/;
230 if $bundling and defined $bopctl{$o} and
231 $bopctl{$o} ne '' and $bopctl{$o} !~ /\@$/;
233 elsif ( ref($optionlist[0]) =~ /^(HASH)$/ ) {
234 $linkage{$o} = shift (@optionlist);
236 if $opctl{$o} ne '' and $opctl{$o} !~ /\%$/;
238 if $bundling and defined $bopctl{$o} and
239 $bopctl{$o} ne '' and $bopctl{$o} !~ /\%$/;
242 $error .= "Invalid option linkage for \"$opt\"\n";
246 # Link to global $opt_XXX variable.
247 # Make sure a valid perl identifier results.
251 print STDERR ("=> link \"$o\" to \@$pkg","::opt_$ov\n")
253 eval ("\$linkage{\$o} = \\\@".$pkg."::opt_$ov;");
255 elsif ( $c =~ /%/ ) {
256 print STDERR ("=> link \"$o\" to \%$pkg","::opt_$ov\n")
258 eval ("\$linkage{\$o} = \\\%".$pkg."::opt_$ov;");
261 print STDERR ("=> link \"$o\" to \$$pkg","::opt_$ov\n")
263 eval ("\$linkage{\$o} = \\\$".$pkg."::opt_$ov;");
268 # Bail out if errors found.
269 die ($error) if $error;
272 # Sort the possible long option names.
273 @opctl = sort(keys (%opctl)) if $autoabbrev;
275 # Show the options tables if debugging.
279 while ( ($k,$v) = each(%opctl) ) {
280 print STDERR ($arrow, "\$opctl{\"$k\"} = \"$v\"\n");
284 while ( ($k,$v) = each(%bopctl) ) {
285 print STDERR ($arrow, "\$bopctl{\"$k\"} = \"$v\"\n");
290 # Process argument list
291 while ( @ARGV > 0 ) {
293 #### Get next argument ####
295 $opt = shift (@ARGV);
298 print STDERR ("=> option \"", $opt, "\"\n") if $debug;
300 #### Determine what we have ####
302 # Double dash is option list terminator.
303 if ( $opt eq $argend ) {
304 # Finish. Push back accumulated arguments and return.
305 unshift (@ARGV, @ret)
306 if $order == $PERMUTE;
307 return ($error == 0);
312 # find_option operates on the GLOBAL $opt and $arg!
313 if ( &$find_option () ) {
315 # find_option undefines $opt in case of errors.
316 next unless defined $opt;
318 if ( defined $arg ) {
319 $opt = $aliases{$opt} if defined $aliases{$opt};
321 if ( defined $linkage{$opt} ) {
322 print STDERR ("=> ref(\$L{$opt}) -> ",
323 ref($linkage{$opt}), "\n") if $debug;
325 if ( ref($linkage{$opt}) eq 'SCALAR' ) {
326 print STDERR ("=> \$\$L{$opt} = \"$arg\"\n") if $debug;
327 ${$linkage{$opt}} = $arg;
329 elsif ( ref($linkage{$opt}) eq 'ARRAY' ) {
330 print STDERR ("=> push(\@{\$L{$opt}, \"$arg\")\n")
332 push (@{$linkage{$opt}}, $arg);
334 elsif ( ref($linkage{$opt}) eq 'HASH' ) {
335 print STDERR ("=> \$\$L{$opt}->{$key} = \"$arg\"\n")
337 $linkage{$opt}->{$key} = $arg;
339 elsif ( ref($linkage{$opt}) eq 'CODE' ) {
340 print STDERR ("=> &L{$opt}(\"$opt\", \"$arg\")\n")
342 &{$linkage{$opt}}($opt, $arg);
345 print STDERR ("Invalid REF type \"", ref($linkage{$opt}),
347 &$croak ("Getopt::Long -- internal error!\n");
350 # No entry in linkage means entry in userlinkage.
352 if ( defined $userlinkage->{$opt} ) {
353 print STDERR ("=> push(\@{\$L{$opt}}, \"$arg\")\n")
355 push (@{$userlinkage->{$opt}}, $arg);
358 print STDERR ("=>\$L{$opt} = [\"$arg\"]\n")
360 $userlinkage->{$opt} = [$arg];
364 if ( defined $userlinkage->{$opt} ) {
365 print STDERR ("=> \$L{$opt}->{$key} = \"$arg\"\n")
367 $userlinkage->{$opt}->{$key} = $arg;
370 print STDERR ("=>\$L{$opt} = {$key => \"$arg\"}\n")
372 $userlinkage->{$opt} = {$key => $arg};
376 print STDERR ("=>\$L{$opt} = \"$arg\"\n") if $debug;
377 $userlinkage->{$opt} = $arg;
382 # Not an option. Save it if we $PERMUTE and don't have a <>.
383 elsif ( $order == $PERMUTE ) {
384 # Try non-options call-back.
386 if ( (defined ($cb = $linkage{'<>'})) ) {
390 print STDERR ("=> saving \"$tryopt\" ",
391 "(not an option, may permute)\n") if $debug;
392 push (@ret, $tryopt);
397 # ...otherwise, terminate.
399 # Push this one back and exit.
400 unshift (@ARGV, $tryopt);
401 return ($error == 0);
407 if ( $order == $PERMUTE ) {
408 # Push back accumulated arguments
409 print STDERR ("=> restoring \"", join('" "', @ret), "\"\n")
410 if $debug && @ret > 0;
411 unshift (@ARGV, @ret) if @ret > 0;
414 return ($error == 0);
420 foreach $opt ( @options ) {
423 if ( $try =~ /^no_?(.*)$/ ) {
427 if ( $try eq 'default' or $try eq 'defaults' ) {
428 &$config_defaults () if $action;
430 elsif ( $try eq 'auto_abbrev' or $try eq 'autoabbrev' ) {
431 $autoabbrev = $action;
433 elsif ( $try eq 'getopt_compat' ) {
434 $getopt_compat = $action;
436 elsif ( $try eq 'ignorecase' or $try eq 'ignore_case' ) {
437 $ignorecase = $action;
439 elsif ( $try eq 'ignore_case_always' ) {
440 $ignorecase = $action ? 2 : 0;
442 elsif ( $try eq 'bundling' ) {
445 elsif ( $try eq 'bundling_override' ) {
446 $bundling = $action ? 2 : 0;
448 elsif ( $try eq 'require_order' ) {
449 $order = $action ? $REQUIRE_ORDER : $PERMUTE;
451 elsif ( $try eq 'permute' ) {
452 $order = $action ? $PERMUTE : $REQUIRE_ORDER;
454 elsif ( $try eq 'pass_through' or $try eq 'passthrough' ) {
455 $passthrough = $action;
457 elsif ( $try eq 'debug' ) {
461 &$croak ("Getopt::Long: unknown config parameter \"$opt\"")
466 # To prevent Carp from being loaded unnecessarily.
469 $Carp::CarpLevel = 1;
473 ################ Private Subroutines ################
477 print STDERR ("=> find \"$opt\", genprefix=\"$genprefix\"\n") if $debug;
479 return 0 unless $opt =~ /^$genprefix(.*)$/;
484 print STDERR ("=> split \"$starter\"+\"$opt\"\n") if $debug;
486 my $optarg = undef; # value supplied with --opt=value
487 my $rest = undef; # remainder from unbundling
489 # If it is a long option, it may include the value.
490 if (($starter eq "--" || ($getopt_compat && !$bundling))
491 && $opt =~ /^([^=]+)=(.*)$/ ) {
494 print STDERR ("=> option \"", $opt,
495 "\", optarg = \"$optarg\"\n") if $debug;
500 my $tryopt = $opt; # option to try
501 my $optbl = \%opctl; # table to look it up (long names)
504 if ( $bundling && $starter eq '-' ) {
505 # Unbundle single letter option.
506 $rest = substr ($tryopt, 1);
507 $tryopt = substr ($tryopt, 0, 1);
508 $tryopt = lc ($tryopt) if $ignorecase > 1;
509 print STDERR ("=> $starter$tryopt unbundled from ",
510 "$starter$tryopt$rest\n") if $debug;
511 $rest = undef unless $rest ne '';
512 $optbl = \%bopctl; # look it up in the short names table
514 # If bundling == 2, long options can override bundles.
515 if ( $bundling == 2 and
516 defined ($type = $opctl{$tryopt.$rest}) ) {
517 print STDERR ("=> $starter$tryopt rebundled to ",
518 "$starter$tryopt$rest\n") if $debug;
524 # Try auto-abbreviation.
525 elsif ( $autoabbrev ) {
526 # Downcase if allowed.
527 $tryopt = $opt = lc ($opt) if $ignorecase;
528 # Turn option name into pattern.
529 my $pat = quotemeta ($opt);
530 # Look up in option names.
531 my @hits = grep (/^$pat/, @opctl);
532 print STDERR ("=> ", scalar(@hits), " hits (@hits) with \"$pat\" ",
533 "out of ", scalar(@opctl), "\n") if $debug;
535 # Check for ambiguous results.
536 unless ( (@hits <= 1) || (grep ($_ eq $opt, @hits) == 1) ) {
537 # See if all matches are for the same option.
540 $_ = $aliases{$_} if defined $aliases{$_};
543 # Now see if it really is ambiguous.
544 unless ( keys(%hit) == 1 ) {
545 return 0 if $passthrough;
546 warn ("Option ", $opt, " is ambiguous (",
547 join(", ", @hits), ")\n");
555 # Complete the option name, if appropriate.
556 if ( @hits == 1 && $hits[0] ne $opt ) {
558 $tryopt = lc ($tryopt) if $ignorecase;
559 print STDERR ("=> option \"$opt\" -> \"$tryopt\"\n")
564 # Map to all lowercase if ignoring case.
565 elsif ( $ignorecase ) {
569 # Check validity by fetching the info.
570 $type = $optbl->{$tryopt} unless defined $type;
571 unless ( defined $type ) {
572 return 0 if $passthrough;
573 warn ("Unknown option: ", $opt, "\n");
579 print STDERR ("=> found \"$type\" for ", $opt, "\n") if $debug;
581 #### Determine argument status ####
583 # If it is an option w/o argument, we're almost finished with it.
584 if ( $type eq '' || $type eq '!' ) {
585 if ( defined $optarg ) {
586 return 0 if $passthrough;
587 warn ("Option ", $opt, " does not take an argument\n");
591 elsif ( $type eq '' ) {
592 $arg = 1; # supply explicit value
595 substr ($opt, 0, 2) = ''; # strip NO prefix
596 $arg = 0; # supply explicit value
598 unshift (@ARGV, $starter.$rest) if defined $rest;
602 # Get mandatory status and type info.
604 ($mand, $type, $array, $hash) = $type =~ /^(.)(.)(@?)(%?)$/;
606 # Check if there is an option argument available.
607 if ( defined $optarg ? ($optarg eq '')
608 : !(defined $rest || @ARGV > 0) ) {
609 # Complain if this option needs an argument.
610 if ( $mand eq "=" ) {
611 return 0 if $passthrough;
612 warn ("Option ", $opt, " requires an argument\n");
616 if ( $mand eq ":" ) {
617 $arg = $type eq "s" ? '' : 0;
622 # Get (possibly optional) argument.
623 $arg = (defined $rest ? $rest
624 : (defined $optarg ? $optarg : shift (@ARGV)));
626 # Get key if this is a "name=value" pair for a hash option.
628 if ($hash && defined $arg) {
629 ($key, $arg) = ($arg =~ /^(.*)=(.*)$/o) ? ($1, $2) : ($arg, 1);
632 #### Check if the argument is valid for this option ####
634 if ( $type eq "s" ) { # string
635 # A mandatory string takes anything.
636 return 1 if $mand eq "=";
638 # An optional string takes almost anything.
639 return 1 if defined $optarg || defined $rest;
640 return 1 if $arg eq "-"; # ??
642 # Check for option or option list terminator.
643 if ($arg eq $argend ||
644 $arg =~ /^$genprefix.+/) {
646 unshift (@ARGV, $arg);
647 # Supply empty value.
652 elsif ( $type eq "n" || $type eq "i" ) { # numeric/integer
653 if ( $bundling && defined $rest && $rest =~ /^(-?[0-9]+)(.*)$/ ) {
656 unshift (@ARGV, $starter.$rest) if defined $rest && $rest ne '';
658 elsif ( $arg !~ /^-?[0-9]+$/ ) {
659 if ( defined $optarg || $mand eq "=" ) {
660 if ( $passthrough ) {
661 unshift (@ARGV, defined $rest ? $starter.$rest : $arg)
662 unless defined $optarg;
665 warn ("Value \"", $arg, "\" invalid for option ",
666 $opt, " (number expected)\n");
670 unshift (@ARGV, $starter.$rest) if defined $rest;
674 unshift (@ARGV, defined $rest ? $starter.$rest : $arg);
675 # Supply default value.
681 elsif ( $type eq "f" ) { # real number, int is also ok
682 # We require at least one digit before a point or 'e',
683 # and at least one digit following the point and 'e'.
685 if ( $bundling && defined $rest &&
686 $rest =~ /^(-?[0-9]+(\.[0-9]+)?([eE]-?[0-9]+)?)(.*)$/ ) {
689 unshift (@ARGV, $starter.$rest) if defined $rest && $rest ne '';
691 elsif ( $arg !~ /^-?[0-9.]+(\.[0-9]+)?([eE]-?[0-9]+)?$/ ) {
692 if ( defined $optarg || $mand eq "=" ) {
693 if ( $passthrough ) {
694 unshift (@ARGV, defined $rest ? $starter.$rest : $arg)
695 unless defined $optarg;
698 warn ("Value \"", $arg, "\" invalid for option ",
699 $opt, " (real number expected)\n");
703 unshift (@ARGV, $starter.$rest) if defined $rest;
707 unshift (@ARGV, defined $rest ? $starter.$rest : $arg);
708 # Supply default value.
714 &$croak ("GetOpt::Long internal error (Can't happen)\n");
719 $config_defaults = sub {
720 # Handle POSIX compliancy.
721 if ( defined $ENV{"POSIXLY_CORRECT"} ) {
722 $gen_prefix = "(--|-)";
723 $autoabbrev = 0; # no automatic abbrev of options
724 $bundling = 0; # no bundling of single letter switches
725 $getopt_compat = 0; # disallow '+' to start options
726 $order = $REQUIRE_ORDER;
729 $gen_prefix = "(--|-|\\+)";
730 $autoabbrev = 1; # automatic abbrev of options
731 $bundling = 0; # bundling off by default
732 $getopt_compat = 1; # allow '+' to start options
735 # Other configurable settings.
736 $debug = 0; # for debugging
737 $error = 0; # error tally
738 $ignorecase = 1; # ignore case when matching options
739 $passthrough = 0; # leave unrecognized options alone
742 ################ Initialization ################
744 # Values for $order. See GNU getopt.c for details.
745 ($REQUIRE_ORDER, $PERMUTE, $RETURN_IN_ORDER) = (0..2);
746 # Version major/minor numbers.
747 ($major_version, $minor_version) = $VERSION =~ /^(\d+)\.(\d+)/;
750 &$config_defaults ();
752 ################ Package return ################
760 GetOptions - extended processing of command line options
765 $result = GetOptions (...option-descriptions...);
769 The Getopt::Long module implements an extended getopt function called
770 GetOptions(). This function adheres to the POSIX syntax for command
771 line options, with GNU extensions. In general, this means that options
772 have long names instead of single letters, and are introduced with a
773 double dash "--". Support for bundling of command line options, as was
774 the case with the more traditional single-letter approach, is provided
775 but not enabled by default. For example, the UNIX "ps" command can be
776 given the command line "option"
780 which means the combination of B<-v>, B<-a> and B<-x>. With the new
781 syntax B<--vax> would be a single option, probably indicating a
782 computer architecture.
784 Command line options can be used to set values. These values can be
785 specified in one of two ways:
790 GetOptions is called with a list of option-descriptions, each of which
791 consists of two elements: the option specifier and the option linkage.
792 The option specifier defines the name of the option and, optionally,
793 the value it can take. The option linkage is usually a reference to a
794 variable that will be set when the option is used. For example, the
795 following call to GetOptions:
797 GetOptions("size=i" => \$offset);
799 will accept a command line option "size" that must have an integer
800 value. With a command line of "--size 24" this will cause the variable
801 $offset to get the value 24.
803 Alternatively, the first argument to GetOptions may be a reference to
804 a HASH describing the linkage for the options, or an object whose
805 class is based on a HASH. The following call is equivalent to the
808 %optctl = ("size" => \$offset);
809 GetOptions(\%optctl, "size=i");
811 Linkage may be specified using either of the above methods, or both.
812 Linkage specified in the argument list takes precedence over the
813 linkage specified in the HASH.
815 The command line options are taken from array @ARGV. Upon completion
816 of GetOptions, @ARGV will contain the rest (i.e. the non-options) of
819 Each option specifier designates the name of the option, optionally
820 followed by an argument specifier.
822 Options that do not take arguments will have no argument specifier.
823 The option variable will be set to 1 if the option is used.
825 For the other options, the values for argument specifiers are:
831 Option does not take an argument and may be negated, i.e. prefixed by
832 "no". E.g. "foo!" will allow B<--foo> (with value 1) and B<-nofoo>
834 The option variable will be set to 1, or 0 if negated.
838 Option takes a mandatory string argument.
839 This string will be assigned to the option variable.
840 Note that even if the string argument starts with B<-> or B<-->, it
841 will not be considered an option on itself.
845 Option takes an optional string argument.
846 This string will be assigned to the option variable.
847 If omitted, it will be assigned "" (an empty string).
848 If the string argument starts with B<-> or B<-->, it
849 will be considered an option on itself.
853 Option takes a mandatory integer argument.
854 This value will be assigned to the option variable.
855 Note that the value may start with B<-> to indicate a negative
860 Option takes an optional integer argument.
861 This value will be assigned to the option variable.
862 If omitted, the value 0 will be assigned.
863 Note that the value may start with B<-> to indicate a negative
868 Option takes a mandatory real number argument.
869 This value will be assigned to the option variable.
870 Note that the value may start with B<-> to indicate a negative
875 Option takes an optional real number argument.
876 This value will be assigned to the option variable.
877 If omitted, the value 0 will be assigned.
881 A lone dash B<-> is considered an option, the corresponding option
882 name is the empty string.
884 A double dash on itself B<--> signals end of the options list.
886 =head2 Linkage specification
888 The linkage specifier is optional. If no linkage is explicitly
889 specified but a ref HASH is passed, GetOptions will place the value in
890 the HASH. For example:
893 GetOptions (\%optctl, "size=i");
895 will perform the equivalent of the assignment
897 $optctl{"size"} = 24;
899 For array options, a reference to an array is used, e.g.:
902 GetOptions (\%optctl, "sizes=i@");
904 with command line "-sizes 24 -sizes 48" will perform the equivalent of
907 $optctl{"sizes"} = [24, 48];
909 For hash options (an option whose argument looks like "name=value"),
910 a reference to a hash is used, e.g.:
913 GetOptions (\%optctl, "define=s%");
915 with command line "--define foo=hello --define bar=world" will perform the
916 equivalent of the assignment
918 $optctl{"define"} = {foo=>'hello', bar=>'world')
920 If no linkage is explicitly specified and no ref HASH is passed,
921 GetOptions will put the value in a global variable named after the
922 option, prefixed by "opt_". To yield a usable Perl variable,
923 characters that are not part of the syntax for variables are
924 translated to underscores. For example, "--fpp-struct-return" will set
925 the variable $opt_fpp_struct_return. Note that this variable resides
926 in the namespace of the calling program, not necessarily B<main>.
929 GetOptions ("size=i", "sizes=i@");
931 with command line "-size 10 -sizes 24 -sizes 48" will perform the
932 equivalent of the assignments
935 @opt_sizes = (24, 48);
937 A lone dash B<-> is considered an option, the corresponding Perl
938 identifier is $opt_ .
940 The linkage specifier can be a reference to a scalar, a reference to
941 an array, a reference to a hash or a reference to a subroutine.
943 If a REF SCALAR is supplied, the new value is stored in the referenced
944 variable. If the option occurs more than once, the previous value is
947 If a REF ARRAY is supplied, the new value is appended (pushed) to the
950 If a REF HASH is supplied, the option value should look like "key" or
951 "key=value" (if the "=value" is omitted then a value of 1 is implied).
952 In this case, the element of the referenced hash with the key "key"
955 If a REF CODE is supplied, the referenced subroutine is called with
956 two arguments: the option name and the option value.
957 The option name is always the true name, not an abbreviation or alias.
959 =head2 Aliases and abbreviations
961 The option name may actually be a list of option names, separated by
962 "|"s, e.g. "foo|bar|blech=s". In this example, "foo" is the true name
963 of this option. If no linkage is specified, options "foo", "bar" and
964 "blech" all will set $opt_foo. For convenience, the single character
965 "?" is allowed as an alias, e.g. "help|?".
967 Option names may be abbreviated to uniqueness, depending on
968 configuration option B<auto_abbrev>.
970 =head2 Non-option call-back routine
972 A special option specifier, E<lt>E<gt>, can be used to designate a subroutine
973 to handle non-option arguments. GetOptions will immediately call this
974 subroutine for every non-option it encounters in the options list.
975 This subroutine gets the name of the non-option passed.
976 This feature requires configuration option B<permute>, see section
977 CONFIGURATION OPTIONS.
979 See also the examples.
981 =head2 Option starters
983 On the command line, options can start with B<-> (traditional), B<-->
984 (POSIX) and B<+> (GNU, now being phased out). The latter is not
985 allowed if the environment variable B<POSIXLY_CORRECT> has been
988 Options that start with "--" may have an argument appended, separated
989 with an "=", e.g. "--foo=bar".
991 =head2 Return values and Errors
993 Configuration errors and errors in the option definitions are
994 signalled using C<die()> and will terminate the calling
995 program unless the call to C<Getopt::Long::GetOptions()> was embedded
996 in C<eval { ... }> or C<die()> was trapped using C<$SIG{__DIE__}>.
998 A return value of 1 (true) indicates success.
1000 A return status of 0 (false) indicates that the function detected one
1001 or more errors during option parsing. These errors are signalled using
1002 C<warn()> and can be trapped with C<$SIG{__WARN__}>.
1004 Errors that can't happen are signalled using C<Carp::croak()>.
1006 =head1 COMPATIBILITY
1008 Getopt::Long::GetOptions() is the successor of
1009 B<newgetopt.pl> that came with Perl 4. It is fully upward compatible.
1010 In fact, the Perl 5 version of newgetopt.pl is just a wrapper around
1013 If an "@" sign is appended to the argument specifier, the option is
1014 treated as an array. Value(s) are not set, but pushed into array
1015 @opt_name. If explicit linkage is supplied, this must be a reference
1018 If an "%" sign is appended to the argument specifier, the option is
1019 treated as a hash. Value(s) of the form "name=value" are set by
1020 setting the element of the hash %opt_name with key "name" to "value"
1021 (if the "=value" portion is omitted it defaults to 1). If explicit
1022 linkage is supplied, this must be a reference to a HASH.
1024 If configuration option B<getopt_compat> is set (see section
1025 CONFIGURATION OPTIONS), options that start with "+" or "-" may also
1026 include their arguments, e.g. "+foo=bar". This is for compatiblity
1027 with older implementations of the GNU "getopt" routine.
1029 If the first argument to GetOptions is a string consisting of only
1030 non-alphanumeric characters, it is taken to specify the option starter
1031 characters. Everything starting with one of these characters from the
1032 starter will be considered an option. B<Using a starter argument is
1033 strongly deprecated.>
1035 For convenience, option specifiers may have a leading B<-> or B<-->,
1036 so it is possible to write:
1038 GetOptions qw(-foo=s --bar=i --ar=s);
1042 If the option specifier is "one:i" (i.e. takes an optional integer
1043 argument), then the following situations are handled:
1045 -one -two -> $opt_one = '', -two is next option
1046 -one -2 -> $opt_one = -2
1048 Also, assume specifiers "foo=s" and "bar:s" :
1050 -bar -xxx -> $opt_bar = '', '-xxx' is next option
1051 -foo -bar -> $opt_foo = '-bar'
1052 -foo -- -> $opt_foo = '--'
1054 In GNU or POSIX format, option names and values can be combined:
1056 +foo=blech -> $opt_foo = 'blech'
1057 --bar= -> $opt_bar = ''
1058 --bar=-- -> $opt_bar = '--'
1060 Example of using variable references:
1062 $ret = GetOptions ('foo=s', \$foo, 'bar=i', 'ar=s', \@ar);
1064 With command line options "-foo blech -bar 24 -ar xx -ar yy"
1065 this will result in:
1071 Example of using the E<lt>E<gt> option specifier:
1073 @ARGV = qw(-foo 1 bar -foo 2 blech);
1074 GetOptions("foo=i", \$myfoo, "<>", \&mysub);
1078 mysub("bar") will be called (with $myfoo being 1)
1079 mysub("blech") will be called (with $myfoo being 2)
1083 @ARGV = qw(-foo 1 bar -foo 2 blech);
1084 GetOptions("foo=i", \$myfoo);
1086 This will leave the non-options in @ARGV:
1089 @ARGV -> qw(bar blech)
1091 =head1 CONFIGURATION OPTIONS
1093 B<GetOptions> can be configured by calling subroutine
1094 B<Getopt::Long::config>. This subroutine takes a list of quoted
1095 strings, each specifying a configuration option to be set, e.g.
1096 B<ignore_case>. Options can be reset by prefixing with B<no_>, e.g.
1097 B<no_ignore_case>. Case does not matter. Multiple calls to B<config>
1100 Previous versions of Getopt::Long used variables for the purpose of
1101 configuring. Although manipulating these variables still work, it
1102 is strongly encouraged to use the new B<config> routine. Besides, it
1105 The following options are available:
1111 This option causes all configuration options to be reset to their
1116 Allow option names to be abbreviated to uniqueness.
1117 Default is set unless environment variable
1118 POSIXLY_CORRECT has been set, in which case B<auto_abbrev> is reset.
1122 Allow '+' to start options.
1123 Default is set unless environment variable
1124 POSIXLY_CORRECT has been set, in which case B<getopt_compat> is reset.
1128 Whether non-options are allowed to be mixed with
1130 Default is set unless environment variable
1131 POSIXLY_CORRECT has been set, in which case b<require_order> is reset.
1133 See also B<permute>, which is the opposite of B<require_order>.
1137 Whether non-options are allowed to be mixed with
1139 Default is set unless environment variable
1140 POSIXLY_CORRECT has been set, in which case B<permute> is reset.
1141 Note that B<permute> is the opposite of B<require_order>.
1143 If B<permute> is set, this means that
1145 -foo arg1 -bar arg2 arg3
1149 -foo -bar arg1 arg2 arg3
1151 If a non-option call-back routine is specified, @ARGV will always be
1152 empty upon succesful return of GetOptions since all options have been
1153 processed, except when B<--> is used:
1155 -foo arg1 -bar arg2 -- arg3
1157 will call the call-back routine for arg1 and arg2, and terminate
1158 leaving arg2 in @ARGV.
1160 If B<require_order> is set, options processing
1161 terminates when the first non-option is encountered.
1163 -foo arg1 -bar arg2 arg3
1167 -foo -- arg1 -bar arg2 arg3
1169 =item bundling (default: reset)
1171 Setting this variable to a non-zero value will allow single-character
1172 options to be bundled. To distinguish bundles from long option names,
1173 long options must be introduced with B<--> and single-character
1174 options (and bundles) with B<->. For example,
1178 would be equivalent to
1182 provided "vax", "v", "a" and "x" have been defined to be valid
1185 Bundled options can also include a value in the bundle; for strings
1186 this value is the rest of the bundle, but integer and floating values
1187 may be combined in the bundle, e.g.
1195 Note: resetting B<bundling> also resets B<bundling_override>.
1197 =item bundling_override (default: reset)
1199 If B<bundling_override> is set, bundling is enabled as with
1200 B<bundling> but now long option names override option bundles. In the
1201 above example, B<-vax> would be interpreted as the option "vax", not
1202 the bundle "v", "a", "x".
1204 Note: resetting B<bundling_override> also resets B<bundling>.
1206 B<Note:> Using option bundling can easily lead to unexpected results,
1207 especially when mixing long options and bundles. Caveat emptor.
1209 =item ignore_case (default: set)
1211 If set, case is ignored when matching options.
1213 Note: resetting B<ignore_case> also resets B<ignore_case_always>.
1215 =item ignore_case_always (default: reset)
1217 When bundling is in effect, case is ignored on single-character
1220 Note: resetting B<ignore_case_always> also resets B<ignore_case>.
1222 =item pass_through (default: reset)
1224 Unknown options are passed through in @ARGV instead of being flagged
1225 as errors. This makes it possible to write wrapper scripts that
1226 process only part of the user supplied options, and passes the
1227 remaining options to some other program.
1229 This can be very confusing, especially when B<permute> is also set.
1231 =item debug (default: reset)
1233 Enable copious debugging output.
1237 =head1 OTHER USEFUL VARIABLES
1241 =item $Getopt::Long::VERSION
1243 The version number of this Getopt::Long implementation in the format
1244 C<major>.C<minor>. This can be used to have Exporter check the
1247 use Getopt::Long 3.00;
1249 You can inspect $Getopt::Long::major_version and
1250 $Getopt::Long::minor_version for the individual components.
1252 =item $Getopt::Long::error
1254 Internal error flag. May be incremented from a call-back routine to
1255 cause options parsing to fail.
1261 Johan Vromans E<lt>jvromans@squirrel.nlE<gt>
1263 =head1 COPYRIGHT AND DISCLAIMER
1265 This program is Copyright 1990,1997 by Johan Vromans.
1266 This program is free software; you can redistribute it and/or
1267 modify it under the terms of the GNU General Public License
1268 as published by the Free Software Foundation; either version 2
1269 of the License, or (at your option) any later version.
1271 This program is distributed in the hope that it will be useful,
1272 but WITHOUT ANY WARRANTY; without even the implied warranty of
1273 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1274 GNU General Public License for more details.
1276 If you do not have a copy of the GNU General Public License write to
1277 the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,