1 # GetOpt::Long.pm -- Universal options parsing
5 # RCS Status : $Id: GetoptLong.pm,v 2.54 2002-02-20 15:00:10+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: Wed Feb 20 15:00:04 2002
13 ################ Copyright ################
15 # This program is Copyright 1990,2002 by Johan Vromans.
16 # This program is free software; you can redistribute it and/or
17 # modify it under the terms of the Perl Artistic License or the
18 # GNU General Public License as published by the Free Software
19 # Foundation; either version 2 of the License, or (at your option) any
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 # GNU General Public License for more details.
27 # If you do not have a copy of the GNU General Public License write to
28 # the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
31 ################ Module Preamble ################
37 use vars qw($VERSION);
39 # For testing versions only.
40 use vars qw($VERSION_STRING);
41 $VERSION_STRING = "2.28";
45 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
49 # Init immediately so their contents can be used in the 'use vars' below.
50 @EXPORT = qw(&GetOptions $REQUIRE_ORDER $PERMUTE $RETURN_IN_ORDER);
54 # User visible variables.
55 use vars @EXPORT, @EXPORT_OK;
56 use vars qw($error $debug $major_version $minor_version);
57 # Deprecated visible variables.
58 use vars qw($autoabbrev $getopt_compat $ignorecase $bundling $order
60 # Official invisible variables.
61 use vars qw($genprefix $caller $gnu_compat);
65 sub config (@); # deprecated name
68 # Private subroutines.
69 sub ConfigDefaults ();
70 sub ParseOptionSpec ($$);
72 sub FindOption ($$$$);
73 sub Croak (@); # demand loading the real Croak
75 ################ Local Variables ################
77 ################ Resident subroutines ################
79 sub ConfigDefaults () {
80 # Handle POSIX compliancy.
81 if ( defined $ENV{"POSIXLY_CORRECT"} ) {
82 $genprefix = "(--|-)";
83 $autoabbrev = 0; # no automatic abbrev of options
84 $bundling = 0; # no bundling of single letter switches
85 $getopt_compat = 0; # disallow '+' to start options
86 $order = $REQUIRE_ORDER;
89 $genprefix = "(--|-|\\+)";
90 $autoabbrev = 1; # automatic abbrev of options
91 $bundling = 0; # bundling off by default
92 $getopt_compat = 1; # allow '+' to start options
95 # Other configurable settings.
96 $debug = 0; # for debugging
97 $error = 0; # error tally
98 $ignorecase = 1; # ignore case when matching options
99 $passthrough = 0; # leave unrecognized options alone
100 $gnu_compat = 0; # require --opt=val if value is optional
105 my $pkg = shift; # package
106 my @syms = (); # symbols to import
107 my @config = (); # configuration
108 my $dest = \@syms; # symbols first
110 if ( $_ eq ':config' ) {
111 $dest = \@config; # config next
114 push (@$dest, $_); # push
116 # Hide one level and call super.
117 local $Exporter::ExportLevel = 1;
118 $pkg->SUPER::import(@syms);
120 Configure (@config) if @config;
123 ################ Initialization ################
125 # Values for $order. See GNU getopt.c for details.
126 ($REQUIRE_ORDER, $PERMUTE, $RETURN_IN_ORDER) = (0..2);
127 # Version major/minor numbers.
128 ($major_version, $minor_version) = $VERSION =~ /^(\d+)\.(\d+)/;
132 ################ OO Interface ################
134 package Getopt::Long::Parser;
136 # NOTE: The object oriented routines use $error for thread locking.
138 lock ($Getopt::Long::error) if $] >= 5.005
141 # Store a copy of the default configuration. Since ConfigDefaults has
142 # just been called, what we get from Configure is the default.
143 my $default_config = do {
145 Getopt::Long::Configure ()
150 my $class = ref($that) || $that;
153 # Register the callers package.
154 my $self = { caller_pkg => (caller)[0] };
156 bless ($self, $class);
158 # Process config attributes.
159 if ( defined $atts{config} ) {
161 my $save = Getopt::Long::Configure ($default_config, @{$atts{config}});
162 $self->{settings} = Getopt::Long::Configure ($save);
163 delete ($atts{config});
165 # Else use default config.
167 $self->{settings} = $default_config;
170 if ( %atts ) { # Oops
171 Getopt::Long::Croak(__PACKAGE__.": unhandled attributes: ".
172 join(" ", sort(keys(%atts))));
183 # Restore settings, merge new settings in.
184 my $save = Getopt::Long::Configure ($self->{settings}, @_);
186 # Restore orig config and save the new config.
187 $self->{settings} = Configure ($save);
195 # Restore config settings.
196 my $save = Getopt::Long::Configure ($self->{settings});
200 $Getopt::Long::caller = $self->{caller_pkg};
203 # Locally set exception handler to default, otherwise it will
204 # be called implicitly here, and again explicitly when we try
205 # to deliver the messages.
206 local ($SIG{__DIE__}) = '__DEFAULT__';
207 $ret = Getopt::Long::GetOptions (@_);
210 # Restore saved settings.
211 Getopt::Long::Configure ($save);
213 # Handle errors and return value.
218 package Getopt::Long;
220 # Indices in option control info.
221 # Note that ParseOptions uses the fields directly. Search for 'hard-wired'.
222 use constant CTL_TYPE => 0;
223 #use constant CTL_TYPE_FLAG => '';
224 #use constant CTL_TYPE_NEG => '!';
225 #use constant CTL_TYPE_INCR => '+';
226 #use constant CTL_TYPE_INT => 'i';
227 #use constant CTL_TYPE_INTINC => 'I';
228 #use constant CTL_TYPE_XINT => 'o';
229 #use constant CTL_TYPE_FLOAT => 'f';
230 #use constant CTL_TYPE_STRING => 's';
232 use constant CTL_CNAME => 1;
234 use constant CTL_MAND => 2;
236 use constant CTL_DEST => 3;
237 use constant CTL_DEST_SCALAR => 0;
238 use constant CTL_DEST_ARRAY => 1;
239 use constant CTL_DEST_HASH => 2;
240 use constant CTL_DEST_CODE => 3;
242 use constant CTL_DEFAULT => 4;
245 #use constant CTL_RANGE => ;
246 #use constant CTL_REPEAT => ;
250 my @optionlist = @_; # local copy of the option descriptions
251 my $argend = '--'; # option list terminator
252 my %opctl = (); # table of option specs
253 my $pkg = $caller || (caller)[0]; # current context
254 # Needed if linkage is omitted.
255 my @ret = (); # accum for non-options
256 my %linkage; # linkage
257 my $userlinkage; # user supplied HASH
258 my $opt; # current option
259 my $prefix = $genprefix; # current prefix
263 print STDERR ("GetOpt::Long $Getopt::Long::VERSION (",
264 '$Revision: 2.54 $', ") ",
265 "called from package \"$pkg\".",
269 "autoabbrev=$autoabbrev,".
270 "bundling=$bundling,",
271 "getopt_compat=$getopt_compat,",
272 "gnu_compat=$gnu_compat,",
275 "ignorecase=$ignorecase,",
276 "passthrough=$passthrough,",
277 "genprefix=\"$genprefix\".",
281 # Check for ref HASH as first argument.
282 # First argument may be an object. It's OK to use this as long
283 # as it is really a hash underneath.
284 $userlinkage = undef;
285 if ( @optionlist && ref($optionlist[0]) and
286 "$optionlist[0]" =~ /^(?:.*\=)?HASH\([^\(]*\)$/ ) {
287 $userlinkage = shift (@optionlist);
288 print STDERR ("=> user linkage: $userlinkage\n") if $debug;
291 # See if the first element of the optionlist contains option
292 # starter characters.
293 # Be careful not to interpret '<>' as option starters.
294 if ( @optionlist && $optionlist[0] =~ /^\W+$/
295 && !($optionlist[0] eq '<>'
297 && ref($optionlist[1])) ) {
298 $prefix = shift (@optionlist);
299 # Turn into regexp. Needs to be parenthesized!
300 $prefix =~ s/(\W)/\\$1/g;
301 $prefix = "([" . $prefix . "])";
302 print STDERR ("=> prefix=\"$prefix\"\n") if $debug;
305 # Verify correctness of optionlist.
307 while ( @optionlist ) {
308 my $opt = shift (@optionlist);
310 # Strip leading prefix so people can specify "--foo=i" if they like.
311 $opt = $+ if $opt =~ /^$prefix+(.*)$/s;
313 if ( $opt eq '<>' ) {
314 if ( (defined $userlinkage)
315 && !(@optionlist > 0 && ref($optionlist[0]))
316 && (exists $userlinkage->{$opt})
317 && ref($userlinkage->{$opt}) ) {
318 unshift (@optionlist, $userlinkage->{$opt});
320 unless ( @optionlist > 0
321 && ref($optionlist[0]) && ref($optionlist[0]) eq 'CODE' ) {
322 $error .= "Option spec <> requires a reference to a subroutine\n";
323 # Kill the linkage (to avoid another error).
325 if @optionlist && ref($optionlist[0]);
328 $linkage{'<>'} = shift (@optionlist);
333 my ($name, $orig) = ParseOptionSpec ($opt, \%opctl);
334 unless ( defined $name ) {
335 # Failed. $orig contains the error message. Sorry for the abuse.
337 # Kill the linkage (to avoid another error).
339 if @optionlist && ref($optionlist[0]);
343 # If no linkage is supplied in the @optionlist, copy it from
344 # the userlinkage if available.
345 if ( defined $userlinkage ) {
346 unless ( @optionlist > 0 && ref($optionlist[0]) ) {
347 if ( exists $userlinkage->{$orig} &&
348 ref($userlinkage->{$orig}) ) {
349 print STDERR ("=> found userlinkage for \"$orig\": ",
350 "$userlinkage->{$orig}\n")
352 unshift (@optionlist, $userlinkage->{$orig});
355 # Do nothing. Being undefined will be handled later.
361 # Copy the linkage. If omitted, link to global variable.
362 if ( @optionlist > 0 && ref($optionlist[0]) ) {
363 print STDERR ("=> link \"$orig\" to $optionlist[0]\n")
365 my $rl = ref($linkage{$orig} = shift (@optionlist));
367 if ( $rl eq "ARRAY" ) {
368 $opctl{$name}[CTL_DEST] = CTL_DEST_ARRAY;
370 elsif ( $rl eq "HASH" ) {
371 $opctl{$name}[CTL_DEST] = CTL_DEST_HASH;
373 elsif ( $rl eq "SCALAR" || $rl eq "CODE" ) {
377 $error .= "Invalid option linkage for \"$opt\"\n";
381 # Link to global $opt_XXX variable.
382 # Make sure a valid perl identifier results.
385 if ( $opctl{$name}[CTL_DEST] == CTL_DEST_ARRAY ) {
386 print STDERR ("=> link \"$orig\" to \@$pkg","::opt_$ov\n")
388 eval ("\$linkage{\$orig} = \\\@".$pkg."::opt_$ov;");
390 elsif ( $opctl{$name}[CTL_DEST] == CTL_DEST_HASH ) {
391 print STDERR ("=> link \"$orig\" to \%$pkg","::opt_$ov\n")
393 eval ("\$linkage{\$orig} = \\\%".$pkg."::opt_$ov;");
396 print STDERR ("=> link \"$orig\" to \$$pkg","::opt_$ov\n")
398 eval ("\$linkage{\$orig} = \\\$".$pkg."::opt_$ov;");
403 # Bail out if errors found.
404 die ($error) if $error;
407 # Show the options tables if debugging.
411 while ( ($k,$v) = each(%opctl) ) {
412 print STDERR ($arrow, "\$opctl{$k} = $v ", OptCtl($v), "\n");
417 # Process argument list
419 while ( $goon && @ARGV > 0 ) {
422 $opt = shift (@ARGV);
423 print STDERR ("=> arg \"", $opt, "\"\n") if $debug;
425 # Double dash is option list terminator.
426 last if $opt eq $argend;
430 my $found; # success status
431 my $key; # key (if hash type)
432 my $arg; # option argument
433 my $ctl; # the opctl entry
435 ($found, $opt, $ctl, $arg, $key) =
436 FindOption ($prefix, $argend, $opt, \%opctl);
440 # FindOption undefines $opt in case of errors.
441 next unless defined $opt;
443 if ( defined $arg ) {
445 # Get the canonical name.
446 print STDERR ("=> cname for \"$opt\" is ") if $debug;
447 $opt = $ctl->[CTL_CNAME];
448 print STDERR ("\"$ctl->[CTL_CNAME]\"\n") if $debug;
450 if ( defined $linkage{$opt} ) {
451 print STDERR ("=> ref(\$L{$opt}) -> ",
452 ref($linkage{$opt}), "\n") if $debug;
454 if ( ref($linkage{$opt}) eq 'SCALAR' ) {
455 if ( $ctl->[CTL_TYPE] eq '+' ) {
456 print STDERR ("=> \$\$L{$opt} += \"$arg\"\n")
458 if ( defined ${$linkage{$opt}} ) {
459 ${$linkage{$opt}} += $arg;
462 ${$linkage{$opt}} = $arg;
466 print STDERR ("=> \$\$L{$opt} = \"$arg\"\n")
468 ${$linkage{$opt}} = $arg;
471 elsif ( ref($linkage{$opt}) eq 'ARRAY' ) {
472 print STDERR ("=> push(\@{\$L{$opt}, \"$arg\")\n")
474 push (@{$linkage{$opt}}, $arg);
476 elsif ( ref($linkage{$opt}) eq 'HASH' ) {
477 print STDERR ("=> \$\$L{$opt}->{$key} = \"$arg\"\n")
479 $linkage{$opt}->{$key} = $arg;
481 elsif ( ref($linkage{$opt}) eq 'CODE' ) {
482 print STDERR ("=> &L{$opt}(\"$opt\"",
483 $ctl->[CTL_DEST] == CTL_DEST_HASH ? ", \"$key\"" : "",
488 local $SIG{__DIE__} = '__DEFAULT__';
489 &{$linkage{$opt}}($opt,
490 $ctl->[CTL_DEST] == CTL_DEST_HASH ? ($key) : (),
493 print STDERR ("=> die($@)\n") if $debug && $@ ne '';
495 if ( $@ =~ /^!FINISH\b/ ) {
505 print STDERR ("Invalid REF type \"", ref($linkage{$opt}),
507 Croak ("Getopt::Long -- internal error!\n");
510 # No entry in linkage means entry in userlinkage.
511 elsif ( $ctl->[CTL_DEST] == CTL_DEST_ARRAY ) {
512 if ( defined $userlinkage->{$opt} ) {
513 print STDERR ("=> push(\@{\$L{$opt}}, \"$arg\")\n")
515 push (@{$userlinkage->{$opt}}, $arg);
518 print STDERR ("=>\$L{$opt} = [\"$arg\"]\n")
520 $userlinkage->{$opt} = [$arg];
523 elsif ( $ctl->[CTL_DEST] == CTL_DEST_HASH ) {
524 if ( defined $userlinkage->{$opt} ) {
525 print STDERR ("=> \$L{$opt}->{$key} = \"$arg\"\n")
527 $userlinkage->{$opt}->{$key} = $arg;
530 print STDERR ("=>\$L{$opt} = {$key => \"$arg\"}\n")
532 $userlinkage->{$opt} = {$key => $arg};
536 if ( $ctl->[CTL_TYPE] eq '+' ) {
537 print STDERR ("=> \$L{$opt} += \"$arg\"\n")
539 if ( defined $userlinkage->{$opt} ) {
540 $userlinkage->{$opt} += $arg;
543 $userlinkage->{$opt} = $arg;
547 print STDERR ("=>\$L{$opt} = \"$arg\"\n") if $debug;
548 $userlinkage->{$opt} = $arg;
554 # Not an option. Save it if we $PERMUTE and don't have a <>.
555 elsif ( $order == $PERMUTE ) {
556 # Try non-options call-back.
558 if ( (defined ($cb = $linkage{'<>'})) ) {
560 print STDERR ("=> &L{$tryopt}(\"$tryopt\")\n")
563 local $SIG{__DIE__} = '__DEFAULT__';
566 print STDERR ("=> die($@)\n") if $debug && $@ ne '';
568 if ( $@ =~ /^!FINISH\b/ ) {
578 print STDERR ("=> saving \"$tryopt\" ",
579 "(not an option, may permute)\n") if $debug;
580 push (@ret, $tryopt);
585 # ...otherwise, terminate.
587 # Push this one back and exit.
588 unshift (@ARGV, $tryopt);
589 return ($error == 0);
595 if ( @ret && $order == $PERMUTE ) {
596 # Push back accumulated arguments
597 print STDERR ("=> restoring \"", join('" "', @ret), "\"\n")
599 unshift (@ARGV, @ret);
602 return ($error == 0);
605 # A readable representation of what's in an optbl.
608 my @v = map { defined($_) ? ($_) : ("<undef>") } @$v;
613 $v[CTL_MAND] ? "O" : "M",
614 ("\$","\@","\%","\&")[$v[CTL_DEST] || 0],
615 "\"$v[CTL_DEFAULT]\"",
616 # $v[CTL_RANGE] || '',
617 # $v[CTL_REPEAT] || '',
621 # Parse an option specification and fill the tables.
622 sub ParseOptionSpec ($$) {
623 my ($opt, $opctl) = @_;
630 # Alias names, or "?"
631 (?: \| (?: \? | \w[-\w]* )? )*
634 # Either modifiers ...
637 # ... or a value/dest specification
640 # ... or an optional-with-default spec
641 : (?: -?\d+ | \+ ) [@%]?
644 return (undef, "Error in option spec: \"$opt\"\n");
647 my ($names, $spec) = ($1, $2);
648 $spec = '' unless defined $spec;
650 # $orig keeps track of the primary name the user specified.
651 # This name will be used for the internal or external linkage.
652 # In other words, if the user specifies "FoO|BaR", it will
653 # match any case combinations of 'foo' and 'bar', but if a global
654 # variable needs to be set, it will be $opt_FoO in the exact case
659 if ( defined $names ) {
660 @names = split (/\|/, $names);
668 # Construct the opctl entries.
670 if ( $spec eq '' || $spec eq '+' || $spec eq '!' ) {
671 # Fields are hard-wired here.
672 $entry = [$spec,$orig,0,CTL_DEST_SCALAR,undef];
674 elsif ( $spec =~ /:(-?\d+|\+)([@%])?/ ) {
677 my $type = $def eq '+' ? 'I' : 'i';
679 $dest = $dest eq '@' ? CTL_DEST_ARRAY
680 : $dest eq '%' ? CTL_DEST_HASH : CTL_DEST_SCALAR;
681 # Fields are hard-wired here.
682 $entry = [$type,$orig,0,$dest,$def eq '+' ? undef : $def];
685 my ($mand, $type, $dest) = $spec =~ /([=:])([ionfs])([@%])?/;
686 $type = 'i' if $type eq 'n';
688 $dest = $dest eq '@' ? CTL_DEST_ARRAY
689 : $dest eq '%' ? CTL_DEST_HASH : CTL_DEST_SCALAR;
690 # Fields are hard-wired here.
691 $entry = [$type,$orig,$mand eq '=',$dest,undef];
694 # Process all names. First is canonical, the rest are aliases.
699 if $ignorecase > (($bundling && length($_) == 1) ? 1 : 0);
701 if ( exists $opctl->{$_} ) {
702 $dups .= "Duplicate specification \"$opt\" for option \"$_\"\n";
705 if ( $spec eq '!' ) {
706 $opctl->{"no$_"} = $entry;
707 $opctl->{$_} = [@$entry];
708 $opctl->{$_}->[CTL_TYPE] = '';
711 $opctl->{$_} = $entry;
715 if ( $dups && $^W ) {
717 $Carp::CarpLevel = 2;
718 foreach ( split(/\n+/, $dups) ) {
726 sub FindOption ($$$$) {
728 # returns (1, $opt, $ctl, $arg, $key) if okay,
729 # returns (1, undef) if option in error,
730 # returns (0) otherwise.
732 my ($prefix, $argend, $opt, $opctl) = @_;
734 print STDERR ("=> find \"$opt\"\n") if $debug;
736 return (0) unless $opt =~ /^$prefix(.*)$/s;
737 return (0) if $opt eq "-" && !defined $opctl->{''};
742 print STDERR ("=> split \"$starter\"+\"$opt\"\n") if $debug;
744 my $optarg; # value supplied with --opt=value
745 my $rest; # remainder from unbundling
747 # If it is a long option, it may include the value.
748 # With getopt_compat, only if not bundling.
749 if ( ($starter eq "--"
750 || ($getopt_compat && ($bundling == 0 || $bundling == 2)))
751 && $opt =~ /^([^=]+)=(.*)$/s ) {
754 print STDERR ("=> option \"", $opt,
755 "\", optarg = \"$optarg\"\n") if $debug;
760 my $tryopt; # option to try
762 if ( $bundling && $starter eq '-' ) {
764 # To try overrides, obey case ignore.
765 $tryopt = $ignorecase ? lc($opt) : $opt;
767 # If bundling == 2, long options can override bundles.
768 if ( $bundling == 2 && length($tryopt) > 1
769 && defined ($opctl->{$tryopt}) ) {
770 print STDERR ("=> $starter$tryopt overrides unbundling\n")
775 # Unbundle single letter option.
776 $rest = length ($tryopt) > 0 ? substr ($tryopt, 1) : '';
777 $tryopt = substr ($tryopt, 0, 1);
778 $tryopt = lc ($tryopt) if $ignorecase > 1;
779 print STDERR ("=> $starter$tryopt unbundled from ",
780 "$starter$tryopt$rest\n") if $debug;
781 $rest = undef unless $rest ne '';
785 # Try auto-abbreviation.
786 elsif ( $autoabbrev ) {
787 # Sort the possible long option names.
788 my @names = sort(keys (%$opctl));
789 # Downcase if allowed.
790 $opt = lc ($opt) if $ignorecase;
792 # Turn option name into pattern.
793 my $pat = quotemeta ($opt);
794 # Look up in option names.
795 my @hits = grep (/^$pat/, @names);
796 print STDERR ("=> ", scalar(@hits), " hits (@hits) with \"$pat\" ",
797 "out of ", scalar(@names), "\n") if $debug;
799 # Check for ambiguous results.
800 unless ( (@hits <= 1) || (grep ($_ eq $opt, @hits) == 1) ) {
801 # See if all matches are for the same option.
804 $_ = $opctl->{$_}->[CTL_CNAME]
805 if defined $opctl->{$_}->[CTL_CNAME];
808 # Now see if it really is ambiguous.
809 unless ( keys(%hit) == 1 ) {
810 return (0) if $passthrough;
811 warn ("Option ", $opt, " is ambiguous (",
812 join(", ", @hits), ")\n");
819 # Complete the option name, if appropriate.
820 if ( @hits == 1 && $hits[0] ne $opt ) {
822 $tryopt = lc ($tryopt) if $ignorecase;
823 print STDERR ("=> option \"$opt\" -> \"$tryopt\"\n")
828 # Map to all lowercase if ignoring case.
829 elsif ( $ignorecase ) {
833 # Check validity by fetching the info.
834 my $ctl = $opctl->{$tryopt};
835 unless ( defined $ctl ) {
836 return (0) if $passthrough;
837 warn ("Unknown option: ", $opt, "\n");
843 print STDERR ("=> found ", OptCtl($ctl),
844 " for \"", $opt, "\"\n") if $debug;
846 #### Determine argument status ####
848 # If it is an option w/o argument, we're almost finished with it.
849 my $type = $ctl->[CTL_TYPE];
852 if ( $type eq '' || $type eq '!' || $type eq '+' ) {
853 if ( defined $optarg ) {
854 return (0) if $passthrough;
855 warn ("Option ", $opt, " does not take an argument\n");
859 elsif ( $type eq '' || $type eq '+' ) {
860 # Supply explicit value.
864 $opt =~ s/^no//i; # strip NO prefix
865 $arg = 0; # supply explicit value
867 unshift (@ARGV, $starter.$rest) if defined $rest;
868 return (1, $opt, $ctl, $arg);
871 # Get mandatory status and type info.
872 my $mand = $ctl->[CTL_MAND];
874 # Check if there is an option argument available.
875 if ( $gnu_compat && defined $optarg && $optarg eq '' ) {
876 return (1, $opt, $ctl, $type eq 's' ? '' : 0) unless $mand;
877 $optarg = 0 unless $type eq 's';
880 # Check if there is an option argument available.
883 : !(defined $rest || @ARGV > 0) ) {
884 # Complain if this option needs an argument.
886 return (0) if $passthrough;
887 warn ("Option ", $opt, " requires an argument\n");
891 if ( $type eq 'I' ) {
892 # Fake incremental type.
895 return (1, $opt, \@c, 1);
897 return (1, $opt, $ctl,
898 defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] :
899 $type eq 's' ? '' : 0);
902 # Get (possibly optional) argument.
903 $arg = (defined $rest ? $rest
904 : (defined $optarg ? $optarg : shift (@ARGV)));
906 # Get key if this is a "name=value" pair for a hash option.
908 if ($ctl->[CTL_DEST] == CTL_DEST_HASH && defined $arg) {
909 ($key, $arg) = ($arg =~ /^([^=]*)=(.*)$/s) ? ($1, $2) : ($arg, 1);
912 #### Check if the argument is valid for this option ####
914 if ( $type eq 's' ) { # string
915 # A mandatory string takes anything.
916 return (1, $opt, $ctl, $arg, $key) if $mand;
918 # An optional string takes almost anything.
919 return (1, $opt, $ctl, $arg, $key)
920 if defined $optarg || defined $rest;
921 return (1, $opt, $ctl, $arg, $key) if $arg eq "-"; # ??
923 # Check for option or option list terminator.
924 if ($arg eq $argend ||
925 $arg =~ /^$prefix.+/) {
927 unshift (@ARGV, $arg);
928 # Supply empty value.
933 elsif ( $type eq 'i' # numeric/integer
934 || $type eq 'I' # numeric/integer w/ incr default
935 || $type eq 'o' ) { # dec/oct/hex/bin value
938 $type eq 'o' ? "[-+]?[1-9][0-9]*|0x[0-9a-f]+|0b[01]+|0[0-7]*"
941 if ( $bundling && defined $rest && $rest =~ /^($o_valid)(.*)$/si ) {
944 $arg = ($type eq 'o' && $arg =~ /^0/) ? oct($arg) : 0+$arg;
945 unshift (@ARGV, $starter.$rest) if defined $rest && $rest ne '';
947 elsif ( $arg =~ /^($o_valid)$/si ) {
948 $arg = ($type eq 'o' && $arg =~ /^0/) ? oct($arg) : 0+$arg;
951 if ( defined $optarg || $mand ) {
952 if ( $passthrough ) {
953 unshift (@ARGV, defined $rest ? $starter.$rest : $arg)
954 unless defined $optarg;
957 warn ("Value \"", $arg, "\" invalid for option ",
959 $type eq 'o' ? "extended " : '',
960 "number expected)\n");
963 unshift (@ARGV, $starter.$rest) if defined $rest;
968 unshift (@ARGV, defined $rest ? $starter.$rest : $arg);
969 if ( $type eq 'I' ) {
970 # Fake incremental type.
973 return (1, $opt, \@c, 1);
975 # Supply default value.
976 $arg = defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] : 0;
981 elsif ( $type eq 'f' ) { # real number, int is also ok
982 # We require at least one digit before a point or 'e',
983 # and at least one digit following the point and 'e'.
985 if ( $bundling && defined $rest &&
986 $rest =~ /^([-+]?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?)(.*)$/s ) {
989 unshift (@ARGV, $starter.$rest) if defined $rest && $rest ne '';
991 elsif ( $arg !~ /^[-+]?[0-9.]+(\.[0-9]+)?([eE][-+]?[0-9]+)?$/ ) {
992 if ( defined $optarg || $mand ) {
993 if ( $passthrough ) {
994 unshift (@ARGV, defined $rest ? $starter.$rest : $arg)
995 unless defined $optarg;
998 warn ("Value \"", $arg, "\" invalid for option ",
999 $opt, " (real number expected)\n");
1002 unshift (@ARGV, $starter.$rest) if defined $rest;
1007 unshift (@ARGV, defined $rest ? $starter.$rest : $arg);
1008 # Supply default value.
1014 Croak ("GetOpt::Long internal error (Can't happen)\n");
1016 return (1, $opt, $ctl, $arg, $key);
1019 # Getopt::Long Configuration.
1024 [ $error, $debug, $major_version, $minor_version,
1025 $autoabbrev, $getopt_compat, $ignorecase, $bundling, $order,
1026 $gnu_compat, $passthrough, $genprefix ];
1028 if ( ref($options[0]) eq 'ARRAY' ) {
1029 ( $error, $debug, $major_version, $minor_version,
1030 $autoabbrev, $getopt_compat, $ignorecase, $bundling, $order,
1031 $gnu_compat, $passthrough, $genprefix ) = @{shift(@options)};
1035 foreach $opt ( @options ) {
1036 my $try = lc ($opt);
1038 if ( $try =~ /^no_?(.*)$/s ) {
1042 if ( ($try eq 'default' or $try eq 'defaults') && $action ) {
1045 elsif ( ($try eq 'posix_default' or $try eq 'posix_defaults') ) {
1046 local $ENV{POSIXLY_CORRECT};
1047 $ENV{POSIXLY_CORRECT} = 1 if $action;
1050 elsif ( $try eq 'auto_abbrev' or $try eq 'autoabbrev' ) {
1051 $autoabbrev = $action;
1053 elsif ( $try eq 'getopt_compat' ) {
1054 $getopt_compat = $action;
1056 elsif ( $try eq 'gnu_getopt' ) {
1064 elsif ( $try eq 'gnu_compat' ) {
1065 $gnu_compat = $action;
1067 elsif ( $try eq 'ignorecase' or $try eq 'ignore_case' ) {
1068 $ignorecase = $action;
1070 elsif ( $try eq 'ignore_case_always' ) {
1071 $ignorecase = $action ? 2 : 0;
1073 elsif ( $try eq 'bundling' ) {
1074 $bundling = $action;
1076 elsif ( $try eq 'bundling_override' ) {
1077 $bundling = $action ? 2 : 0;
1079 elsif ( $try eq 'require_order' ) {
1080 $order = $action ? $REQUIRE_ORDER : $PERMUTE;
1082 elsif ( $try eq 'permute' ) {
1083 $order = $action ? $PERMUTE : $REQUIRE_ORDER;
1085 elsif ( $try eq 'pass_through' or $try eq 'passthrough' ) {
1086 $passthrough = $action;
1088 elsif ( $try =~ /^prefix=(.+)$/ && $action ) {
1090 # Turn into regexp. Needs to be parenthesized!
1091 $genprefix = "(" . quotemeta($genprefix) . ")";
1092 eval { '' =~ /$genprefix/; };
1093 Croak ("Getopt::Long: invalid pattern \"$genprefix\"") if $@;
1095 elsif ( $try =~ /^prefix_pattern=(.+)$/ && $action ) {
1097 # Parenthesize if needed.
1098 $genprefix = "(" . $genprefix . ")"
1099 unless $genprefix =~ /^\(.*\)$/;
1100 eval { '' =~ /$genprefix/; };
1101 Croak ("Getopt::Long: invalid pattern \"$genprefix\"") if $@;
1103 elsif ( $try eq 'debug' ) {
1107 Croak ("Getopt::Long: unknown config parameter \"$opt\"")
1118 # To prevent Carp from being loaded unnecessarily.
1121 $Carp::CarpLevel = 1;
1125 ################ Documentation ################
1129 Getopt::Long - Extended processing of command line options
1134 my $data = "file.dat";
1137 $result = GetOptions ("length=i" => \$length, # numeric
1138 "file=s" => \$data, # string
1139 "verbose" => \$verbose); # flag
1143 The Getopt::Long module implements an extended getopt function called
1144 GetOptions(). This function adheres to the POSIX syntax for command
1145 line options, with GNU extensions. In general, this means that options
1146 have long names instead of single letters, and are introduced with a
1147 double dash "--". Support for bundling of command line options, as was
1148 the case with the more traditional single-letter approach, is provided
1149 but not enabled by default.
1151 =head1 Command Line Options, an Introduction
1153 Command line operated programs traditionally take their arguments from
1154 the command line, for example filenames or other information that the
1155 program needs to know. Besides arguments, these programs often take
1156 command line I<options> as well. Options are not necessary for the
1157 program to work, hence the name 'option', but are used to modify its
1158 default behaviour. For example, a program could do its job quietly,
1159 but with a suitable option it could provide verbose information about
1162 Command line options come in several flavours. Historically, they are
1163 preceded by a single dash C<->, and consist of a single letter.
1167 Usually, these single-character options can be bundled:
1171 Options can have values, the value is placed after the option
1172 character. Sometimes with whitespace in between, sometimes not:
1176 Due to the very cryptic nature of these options, another style was
1177 developed that used long names. So instead of a cryptic C<-l> one
1178 could use the more descriptive C<--long>. To distinguish between a
1179 bundle of single-character options and a long one, two dashes are used
1180 to precede the option name. Early implementations of long options used
1181 a plus C<+> instead. Also, option values could be specified either
1190 The C<+> form is now obsolete and strongly deprecated.
1192 =head1 Getting Started with Getopt::Long
1194 Getopt::Long is the Perl5 successor of C<newgetopt.pl>. This was
1195 the first Perl module that provided support for handling the new style
1196 of command line options, hence the name Getopt::Long. This module
1197 also supports single-character options and bundling. In this case, the
1198 options are restricted to alphabetic characters only, and the
1199 characters C<?> and C<->.
1201 To use Getopt::Long from a Perl program, you must include the
1202 following line in your Perl program:
1206 This will load the core of the Getopt::Long module and prepare your
1207 program for using it. Most of the actual Getopt::Long code is not
1208 loaded until you really call one of its functions.
1210 In the default configuration, options names may be abbreviated to
1211 uniqueness, case does not matter, and a single dash is sufficient,
1212 even for long option names. Also, options may be placed between
1213 non-option arguments. See L<Configuring Getopt::Long> for more
1214 details on how to configure Getopt::Long.
1216 =head2 Simple options
1218 The most simple options are the ones that take no values. Their mere
1219 presence on the command line enables the option. Popular examples are:
1221 --all --verbose --quiet --debug
1223 Handling simple options is straightforward:
1225 my $verbose = ''; # option variable with default value (false)
1226 my $all = ''; # option variable with default value (false)
1227 GetOptions ('verbose' => \$verbose, 'all' => \$all);
1229 The call to GetOptions() parses the command line arguments that are
1230 present in C<@ARGV> and sets the option variable to the value C<1> if
1231 the option did occur on the command line. Otherwise, the option
1232 variable is not touched. Setting the option value to true is often
1233 called I<enabling> the option.
1235 The option name as specified to the GetOptions() function is called
1236 the option I<specification>. Later we'll see that this specification
1237 can contain more than just the option name. The reference to the
1238 variable is called the option I<destination>.
1240 GetOptions() will return a true value if the command line could be
1241 processed successfully. Otherwise, it will write error messages to
1242 STDERR, and return a false result.
1244 =head2 A little bit less simple options
1246 Getopt::Long supports two useful variants of simple options:
1247 I<negatable> options and I<incremental> options.
1249 A negatable option is specified with an exclamation mark C<!> after the
1252 my $verbose = ''; # option variable with default value (false)
1253 GetOptions ('verbose!' => \$verbose);
1255 Now, using C<--verbose> on the command line will enable C<$verbose>,
1256 as expected. But it is also allowed to use C<--noverbose>, which will
1257 disable C<$verbose> by setting its value to C<0>. Using a suitable
1258 default value, the program can find out whether C<$verbose> is false
1259 by default, or disabled by using C<--noverbose>.
1261 An incremental option is specified with a plus C<+> after the
1264 my $verbose = ''; # option variable with default value (false)
1265 GetOptions ('verbose+' => \$verbose);
1267 Using C<--verbose> on the command line will increment the value of
1268 C<$verbose>. This way the program can keep track of how many times the
1269 option occurred on the command line. For example, each occurrence of
1270 C<--verbose> could increase the verbosity level of the program.
1272 =head2 Mixing command line option with other arguments
1274 Usually programs take command line options as well as other arguments,
1275 for example, file names. It is good practice to always specify the
1276 options first, and the other arguments last. Getopt::Long will,
1277 however, allow the options and arguments to be mixed and 'filter out'
1278 all the options before passing the rest of the arguments to the
1279 program. To stop Getopt::Long from processing further arguments,
1280 insert a double dash C<--> on the command line:
1284 In this example, C<--all> will I<not> be treated as an option, but
1285 passed to the program unharmed, in C<@ARGV>.
1287 =head2 Options with values
1289 For options that take values it must be specified whether the option
1290 value is required or not, and what kind of value the option expects.
1292 Three kinds of values are supported: integer numbers, floating point
1293 numbers, and strings.
1295 If the option value is required, Getopt::Long will take the
1296 command line argument that follows the option and assign this to the
1297 option variable. If, however, the option value is specified as
1298 optional, this will only be done if that value does not look like a
1299 valid command line option itself.
1301 my $tag = ''; # option variable with default value
1302 GetOptions ('tag=s' => \$tag);
1304 In the option specification, the option name is followed by an equals
1305 sign C<=> and the letter C<s>. The equals sign indicates that this
1306 option requires a value. The letter C<s> indicates that this value is
1307 an arbitrary string. Other possible value types are C<i> for integer
1308 values, and C<f> for floating point values. Using a colon C<:> instead
1309 of the equals sign indicates that the option value is optional. In
1310 this case, if no suitable value is supplied, string valued options get
1311 an empty string C<''> assigned, while numeric options are set to C<0>.
1313 =head2 Options with multiple values
1315 Options sometimes take several values. For example, a program could
1316 use multiple directories to search for library files:
1318 --library lib/stdlib --library lib/extlib
1320 To accomplish this behaviour, simply specify an array reference as the
1321 destination for the option:
1324 GetOptions ("library=s" => \@libfiles);
1326 Used with the example above, C<@libfiles> would contain two strings
1327 upon completion: C<"lib/srdlib"> and C<"lib/extlib">, in that order.
1328 It is also possible to specify that only integer or floating point
1329 numbers are acceptible values.
1331 Often it is useful to allow comma-separated lists of values as well as
1332 multiple occurrences of the options. This is easy using Perl's split()
1333 and join() operators:
1336 GetOptions ("library=s" => \@libfiles);
1337 @libfiles = split(/,/,join(',',@libfiles));
1339 Of course, it is important to choose the right separator string for
1342 =head2 Options with hash values
1344 If the option destination is a reference to a hash, the option will
1345 take, as value, strings of the form I<key>C<=>I<value>. The value will
1346 be stored with the specified key in the hash.
1349 GetOptions ("define=s" => \%defines);
1351 When used with command line options:
1353 --define os=linux --define vendor=redhat
1355 the hash C<%defines> will contain two keys, C<"os"> with value
1356 C<"linux> and C<"vendor"> with value C<"redhat">.
1357 It is also possible to specify that only integer or floating point
1358 numbers are acceptible values. The keys are always taken to be strings.
1360 =head2 User-defined subroutines to handle options
1362 Ultimate control over what should be done when (actually: each time)
1363 an option is encountered on the command line can be achieved by
1364 designating a reference to a subroutine (or an anonymous subroutine)
1365 as the option destination. When GetOptions() encounters the option, it
1366 will call the subroutine with two or three arguments. The first
1367 argument is the name of the option. For a scalar or array destination,
1368 the second argument is the value to be stored. For a hash destination,
1369 the second arguments is the key to the hash, and the third argument
1370 the value to be stored. It is up to the subroutine to store the value,
1371 or do whatever it thinks is appropriate.
1373 A trivial application of this mechanism is to implement options that
1374 are related to each other. For example:
1376 my $verbose = ''; # option variable with default value (false)
1377 GetOptions ('verbose' => \$verbose,
1378 'quiet' => sub { $verbose = 0 });
1380 Here C<--verbose> and C<--quiet> control the same variable
1381 C<$verbose>, but with opposite values.
1383 If the subroutine needs to signal an error, it should call die() with
1384 the desired error message as its argument. GetOptions() will catch the
1385 die(), issue the error message, and record that an error result must
1386 be returned upon completion.
1388 If the text of the error message starts with an exclamantion mark C<!>
1389 it is interpreted specially by GetOptions(). There is currently one
1390 special command implemented: C<die("!FINISH")> will cause GetOptions()
1391 to stop processing options, as if it encountered a double dash C<-->.
1393 =head2 Options with multiple names
1395 Often it is user friendly to supply alternate mnemonic names for
1396 options. For example C<--height> could be an alternate name for
1397 C<--length>. Alternate names can be included in the option
1398 specification, separated by vertical bar C<|> characters. To implement
1401 GetOptions ('length|height=f' => \$length);
1403 The first name is called the I<primary> name, the other names are
1406 Multiple alternate names are possible.
1408 =head2 Case and abbreviations
1410 Without additional configuration, GetOptions() will ignore the case of
1411 option names, and allow the options to be abbreviated to uniqueness.
1413 GetOptions ('length|height=f' => \$length, "head" => \$head);
1415 This call will allow C<--l> and C<--L> for the length option, but
1416 requires a least C<--hea> and C<--hei> for the head and height options.
1418 =head2 Summary of Option Specifications
1420 Each option specifier consists of two parts: the name specification
1421 and the argument specification.
1423 The name specification contains the name of the option, optionally
1424 followed by a list of alternative names separated by vertical bar
1427 length option name is "length"
1428 length|size|l name is "length", aliases are "size" and "l"
1430 The argument specification is optional. If omitted, the option is
1431 considered boolean, a value of 1 will be assigned when the option is
1432 used on the command line.
1434 The argument specification can be
1440 The option does not take an argument and may be negated, i.e. prefixed
1441 by "no". E.g. C<"foo!"> will allow C<--foo> (a value of 1 will be
1442 assigned) and C<--nofoo> (a value of 0 will be assigned). If the
1443 option has aliases, this applies to the aliases as well.
1445 Using negation on a single letter option when bundling is in effect is
1446 pointless and will result in a warning.
1450 The option does not take an argument and will be incremented by 1
1451 every time it appears on the command line. E.g. C<"more+">, when used
1452 with C<--more --more --more>, will increment the value three times,
1453 resulting in a value of 3 (provided it was 0 or undefined at first).
1455 The C<+> specifier is ignored if the option destination is not a scalar.
1457 =item = I<type> [ I<desttype> ]
1459 The option requires an argument of the given type. Supported types
1466 String. An arbitrary sequence of characters. It is valid for the
1467 argument to start with C<-> or C<-->.
1471 Integer. An optional leading plus or minus sign, followed by a
1476 Extended integer, Perl style. This can be either an optional leading
1477 plus or minus sign, followed by a sequence of digits, or an octal
1478 string (a zero, optionally followed by '0', '1', .. '7'), or a
1479 hexadecimal string (C<0x> followed by '0' .. '9', 'a' .. 'f', case
1480 insensitive), or a binary string (C<0b> followed by a series of '0'
1485 Real number. For example C<3.14>, C<-6.23E24> and so on.
1489 The I<desttype> can be C<@> or C<%> to specify that the option is
1490 list or a hash valued. This is only needed when the destination for
1491 the option value is not otherwise specified. It should be omitted when
1494 =item : I<type> [ I<desttype> ]
1496 Like C<=>, but designates the argument as optional.
1497 If omitted, an empty string will be assigned to string values options,
1498 and the value zero to numeric options.
1500 Note that if a string argument starts with C<-> or C<-->, it will be
1501 considered an option on itself.
1503 =item : I<number> [ I<desttype> ]
1505 Like C<:i>, but if the value is omitted, the I<number> will be assigned.
1507 =item : + [ I<desttype> ]
1509 Like C<:i>, but if the value is omitted, the current value for the
1510 option will be incremented.
1514 =head1 Advanced Possibilities
1516 =head2 Object oriented interface
1518 Getopt::Long can be used in an object oriented way as well:
1521 $p = new Getopt::Long::Parser;
1522 $p->configure(...configuration options...);
1523 if ($p->getoptions(...options descriptions...)) ...
1525 Configuration options can be passed to the constructor:
1527 $p = new Getopt::Long::Parser
1528 config => [...configuration options...];
1530 For thread safety, each method call will acquire an exclusive lock to
1531 the Getopt::Long module. So don't call these methods from a callback
1534 =head2 Documentation and help texts
1536 Getopt::Long encourages the use of Pod::Usage to produce help
1537 messages. For example:
1545 GetOptions('help|?' => \$help, man => \$man) or pod2usage(2);
1546 pod2usage(1) if $help;
1547 pod2usage(-exitstatus => 0, -verbose => 2) if $man;
1553 sample - Using GetOpt::Long and Pod::Usage
1557 sample [options] [file ...]
1560 -help brief help message
1561 -man full documentation
1569 Print a brief help message and exits.
1573 Prints the manual page and exits.
1579 B<This program> will read the given input file(s) and do someting
1580 useful with the contents thereof.
1584 See L<Pod::Usage> for details.
1586 =head2 Storing options in a hash
1588 Sometimes, for example when there are a lot of options, having a
1589 separate variable for each of them can be cumbersome. GetOptions()
1590 supports, as an alternative mechanism, storing options in a hash.
1592 To obtain this, a reference to a hash must be passed I<as the first
1593 argument> to GetOptions(). For each option that is specified on the
1594 command line, the option value will be stored in the hash with the
1595 option name as key. Options that are not actually used on the command
1596 line will not be put in the hash, on other words,
1597 C<exists($h{option})> (or defined()) can be used to test if an option
1598 was used. The drawback is that warnings will be issued if the program
1599 runs under C<use strict> and uses C<$h{option}> without testing with
1600 exists() or defined() first.
1603 GetOptions (\%h, 'length=i'); # will store in $h{length}
1605 For options that take list or hash values, it is necessary to indicate
1606 this by appending an C<@> or C<%> sign after the type:
1608 GetOptions (\%h, 'colours=s@'); # will push to @{$h{colours}}
1610 To make things more complicated, the hash may contain references to
1611 the actual destinations, for example:
1614 my %h = ('length' => \$len);
1615 GetOptions (\%h, 'length=i'); # will store in $len
1617 This example is fully equivalent with:
1620 GetOptions ('length=i' => \$len); # will store in $len
1622 Any mixture is possible. For example, the most frequently used options
1623 could be stored in variables while all other options get stored in the
1626 my $verbose = 0; # frequently referred
1627 my $debug = 0; # frequently referred
1628 my %h = ('verbose' => \$verbose, 'debug' => \$debug);
1629 GetOptions (\%h, 'verbose', 'debug', 'filter', 'size=i');
1630 if ( $verbose ) { ... }
1631 if ( exists $h{filter} ) { ... option 'filter' was specified ... }
1635 With bundling it is possible to set several single-character options
1636 at once. For example if C<a>, C<v> and C<x> are all valid options,
1640 would set all three.
1642 Getopt::Long supports two levels of bundling. To enable bundling, a
1643 call to Getopt::Long::Configure is required.
1645 The first level of bundling can be enabled with:
1647 Getopt::Long::Configure ("bundling");
1649 Configured this way, single-character options can be bundled but long
1650 options B<must> always start with a double dash C<--> to avoid
1651 abiguity. For example, when C<vax>, C<a>, C<v> and C<x> are all valid
1656 would set C<a>, C<v> and C<x>, but
1662 The second level of bundling lifts this restriction. It can be enabled
1665 Getopt::Long::Configure ("bundling_override");
1667 Now, C<-vax> would set the option C<vax>.
1669 When any level of bundling is enabled, option values may be inserted
1670 in the bundle. For example:
1678 When configured for bundling, single-character options are matched
1679 case sensitive while long options are matched case insensitive. To
1680 have the single-character options matched case insensitive as well,
1683 Getopt::Long::Configure ("bundling", "ignorecase_always");
1685 It goes without saying that bundling can be quite confusing.
1687 =head2 The lonesome dash
1689 Normally, a lone dash C<-> on the command line will not be considered
1690 an option. Option processing will terminate (unless "permute" is
1691 configured) and the dash will be left in C<@ARGV>.
1693 It is possible to get special treatment for a lone dash. This can be
1694 achieved by adding an option specification with an empty name, for
1697 GetOptions ('' => \$stdio);
1699 A lone dash on the command line will now be a legal option, and using
1700 it will set variable C<$stdio>.
1702 =head2 Argument callback
1704 A special option 'name' C<<>> can be used to designate a subroutine
1705 to handle non-option arguments. When GetOptions() encounters an
1706 argument that does not look like an option, it will immediately call this
1707 subroutine and passes it one parameter: the argument name.
1713 GetOptions ('width=i' => \$width, '<>' => \&process);
1715 When applied to the following command line:
1717 arg1 --width=72 arg2 --width=60 arg3
1720 C<process("arg1")> while C<$width> is C<80>,
1721 C<process("arg2")> while C<$width> is C<72>, and
1722 C<process("arg3")> while C<$width> is C<60>.
1724 This feature requires configuration option B<permute>, see section
1725 L<Configuring Getopt::Long>.
1728 =head1 Configuring Getopt::Long
1730 Getopt::Long can be configured by calling subroutine
1731 Getopt::Long::Configure(). This subroutine takes a list of quoted
1732 strings, each specifying a configuration option to be enabled, e.g.
1733 C<ignore_case>, or disabled, e.g. C<no_ignore_case>. Case does not
1734 matter. Multiple calls to Configure() are possible.
1736 Alternatively, as of version 2.24, the configuration options may be
1737 passed together with the C<use> statement:
1739 use Getopt::Long qw(:config no_ignore_case bundling);
1741 The following options are available:
1747 This option causes all configuration options to be reset to their
1752 This option causes all configuration options to be reset to their
1753 default values as if the environment variable POSIXLY_CORRECT had
1758 Allow option names to be abbreviated to uniqueness.
1759 Default is enabled unless environment variable
1760 POSIXLY_CORRECT has been set, in which case C<auto_abbrev> is disabled.
1764 Allow C<+> to start options.
1765 Default is enabled unless environment variable
1766 POSIXLY_CORRECT has been set, in which case C<getopt_compat> is disabled.
1770 C<gnu_compat> controls whether C<--opt=> is allowed, and what it should
1771 do. Without C<gnu_compat>, C<--opt=> gives an error. With C<gnu_compat>,
1772 C<--opt=> will give option C<opt> and empty value.
1773 This is the way GNU getopt_long() does it.
1777 This is a short way of setting C<gnu_compat> C<bundling> C<permute>
1778 C<no_getopt_compat>. With C<gnu_getopt>, command line handling should be
1779 fully compatible with GNU getopt_long().
1783 Whether command line arguments are allowed to be mixed with options.
1784 Default is disabled unless environment variable
1785 POSIXLY_CORRECT has been set, in which case C<require_order> is enabled.
1787 See also C<permute>, which is the opposite of C<require_order>.
1791 Whether command line arguments are allowed to be mixed with options.
1792 Default is enabled unless environment variable
1793 POSIXLY_CORRECT has been set, in which case C<permute> is disabled.
1794 Note that C<permute> is the opposite of C<require_order>.
1796 If C<permute> is enabled, this means that
1798 --foo arg1 --bar arg2 arg3
1802 --foo --bar arg1 arg2 arg3
1804 If an argument callback routine is specified, C<@ARGV> will always be
1805 empty upon succesful return of GetOptions() since all options have been
1806 processed. The only exception is when C<--> is used:
1808 --foo arg1 --bar arg2 -- arg3
1810 This will call the callback routine for arg1 and arg2, and then
1811 terminate GetOptions() leaving C<"arg2"> in C<@ARGV>.
1813 If C<require_order> is enabled, options processing
1814 terminates when the first non-option is encountered.
1816 --foo arg1 --bar arg2 arg3
1820 --foo -- arg1 --bar arg2 arg3
1822 If C<pass_through> is also enabled, options processing will terminate
1823 at the first unrecognized option, or non-option, whichever comes
1826 =item bundling (default: disabled)
1828 Enabling this option will allow single-character options to be
1829 bundled. To distinguish bundles from long option names, long options
1830 I<must> be introduced with C<--> and bundles with C<->.
1832 Note that, if you have options C<a>, C<l> and C<all>, and
1833 auto_abbrev enabled, possible arguments and option settings are:
1835 using argument sets option(s)
1836 ------------------------------------------
1839 -al, -la, -ala, -all,... a, l
1842 The suprising part is that C<--a> sets option C<a> (due to auto
1843 completion), not C<all>.
1845 Note: disabling C<bundling> also disables C<bundling_override>.
1847 =item bundling_override (default: disabled)
1849 If C<bundling_override> is enabled, bundling is enabled as with
1850 C<bundling> but now long option names override option bundles.
1852 Note: disabling C<bundling_override> also disables C<bundling>.
1854 B<Note:> Using option bundling can easily lead to unexpected results,
1855 especially when mixing long options and bundles. Caveat emptor.
1857 =item ignore_case (default: enabled)
1859 If enabled, case is ignored when matching long option names. If,
1860 however, bundling is enabled as well, single character options will be
1861 treated case-sensitive.
1863 With C<ignore_case>, option specifications for options that only
1864 differ in case, e.g., C<"foo"> and C<"Foo">, will be flagged as
1867 Note: disabling C<ignore_case> also disables C<ignore_case_always>.
1869 =item ignore_case_always (default: disabled)
1871 When bundling is in effect, case is ignored on single-character
1874 Note: disabling C<ignore_case_always> also disables C<ignore_case>.
1876 =item pass_through (default: disabled)
1878 Options that are unknown, ambiguous or supplied with an invalid option
1879 value are passed through in C<@ARGV> instead of being flagged as
1880 errors. This makes it possible to write wrapper scripts that process
1881 only part of the user supplied command line arguments, and pass the
1882 remaining options to some other program.
1884 If C<require_order> is enabled, options processing will terminate at
1885 the first unrecognized option, or non-option, whichever comes first.
1886 However, if C<permute> is enabled instead, results can become confusing.
1890 The string that starts options. If a constant string is not
1891 sufficient, see C<prefix_pattern>.
1893 =item prefix_pattern
1895 A Perl pattern that identifies the strings that introduce options.
1896 Default is C<(--|-|\+)> unless environment variable
1897 POSIXLY_CORRECT has been set, in which case it is C<(--|-)>.
1899 =item debug (default: disabled)
1901 Enable debugging output.
1905 =head1 Return values and Errors
1907 Configuration errors and errors in the option definitions are
1908 signalled using die() and will terminate the calling program unless
1909 the call to Getopt::Long::GetOptions() was embedded in C<eval { ...
1910 }>, or die() was trapped using C<$SIG{__DIE__}>.
1912 GetOptions returns true to indicate success.
1913 It returns false when the function detected one or more errors during
1914 option parsing. These errors are signalled using warn() and can be
1915 trapped with C<$SIG{__WARN__}>.
1917 Errors that can't happen are signalled using Carp::croak().
1921 The earliest development of C<newgetopt.pl> started in 1990, with Perl
1922 version 4. As a result, its development, and the development of
1923 Getopt::Long, has gone through several stages. Since backward
1924 compatibility has always been extremely important, the current version
1925 of Getopt::Long still supports a lot of constructs that nowadays are
1926 no longer necessary or otherwise unwanted. This section describes
1927 briefly some of these 'features'.
1929 =head2 Default destinations
1931 When no destination is specified for an option, GetOptions will store
1932 the resultant value in a global variable named C<opt_>I<XXX>, where
1933 I<XXX> is the primary name of this option. When a progam executes
1934 under C<use strict> (recommended), these variables must be
1935 pre-declared with our() or C<use vars>.
1937 our $opt_length = 0;
1938 GetOptions ('length=i'); # will store in $opt_length
1940 To yield a usable Perl variable, characters that are not part of the
1941 syntax for variables are translated to underscores. For example,
1942 C<--fpp-struct-return> will set the variable
1943 C<$opt_fpp_struct_return>. Note that this variable resides in the
1944 namespace of the calling program, not necessarily C<main>. For
1947 GetOptions ("size=i", "sizes=i@");
1949 with command line "-size 10 -sizes 24 -sizes 48" will perform the
1950 equivalent of the assignments
1953 @opt_sizes = (24, 48);
1955 =head2 Alternative option starters
1957 A string of alternative option starter characters may be passed as the
1958 first argument (or the first argument after a leading hash reference
1962 GetOptions ('/', 'length=i' => $len);
1964 Now the command line may look like:
1968 Note that to terminate options processing still requires a double dash
1971 GetOptions() will not interpret a leading C<< "<>" >> as option starters
1972 if the next argument is a reference. To force C<< "<" >> and C<< ">" >> as
1973 option starters, use C<< "><" >>. Confusing? Well, B<using a starter
1974 argument is strongly deprecated> anyway.
1976 =head2 Configuration variables
1978 Previous versions of Getopt::Long used variables for the purpose of
1979 configuring. Although manipulating these variables still work, it is
1980 strongly encouraged to use the C<Configure> routine that was introduced
1981 in version 2.17. Besides, it is much easier.
1983 =head1 Trouble Shooting
1985 =head2 Warning: Ignoring '!' modifier for short option
1987 This warning is issued when the '!' modifier is applied to a short
1988 (one-character) option and bundling is in effect. E.g.,
1990 Getopt::Long::Configure("bundling");
1991 GetOptions("foo|f!" => \$foo);
1993 Note that older Getopt::Long versions did not issue a warning, because
1994 the '!' modifier was applied to the first name only. This bug was
1997 Solution: separate the long and short names and apply the '!' to the
1998 long names only, e.g.,
2000 GetOptions("foo!" => \$foo, "f" => \$foo);
2002 =head2 GetOptions does not return a false result when an option is not supplied
2004 That's why they're called 'options'.
2006 =head2 GetOptions does not split the command line correctly
2008 The command line is not split by GetOptions, but by the command line
2009 interpreter (CLI). On Unix, this is the shell. On Windows, it is
2010 COMMAND.COM or CMD.EXE. Other operating systems have other CLIs.
2012 It is important to know that these CLIs may behave different when the
2013 command line contains special characters, in particular quotes or
2014 backslashes. For example, with Unix shells you can use single quotes
2015 (C<'>) and double quotes (C<">) to group words together. The following
2016 alternatives are equivalent on Unix:
2022 In case of doubt, insert the following statement in front of your Perl
2025 print STDERR (join("|",@ARGV),"\n");
2027 to verify how your CLI passes the arguments to the program.
2029 =head2 How do I put a "-?" option into a Getopt::Long?
2031 You can only obtain this using an alias, and Getopt::Long of at least
2035 GetOptions ("help|?"); # -help and -? will both set $opt_help
2039 Johan Vromans <jvromans@squirrel.nl>
2041 =head1 COPYRIGHT AND DISCLAIMER
2043 This program is Copyright 2002,1990 by Johan Vromans.
2044 This program is free software; you can redistribute it and/or
2045 modify it under the terms of the Perl Artistic License or the
2046 GNU General Public License as published by the Free Software
2047 Foundation; either version 2 of the License, or (at your option) any
2050 This program is distributed in the hope that it will be useful,
2051 but WITHOUT ANY WARRANTY; without even the implied warranty of
2052 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2053 GNU General Public License for more details.
2055 If you do not have a copy of the GNU General Public License write to
2056 the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,