1 # GetOpt::Long.pm -- Universal options parsing
5 # RCS Status : $Id: GetoptLong.pm,v 2.55 2002-03-13 13:06:44+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 Mar 13 12:54:01 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.29";
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 ($$$$);
74 ################ Local Variables ################
76 ################ Resident subroutines ################
78 sub ConfigDefaults () {
79 # Handle POSIX compliancy.
80 if ( defined $ENV{"POSIXLY_CORRECT"} ) {
81 $genprefix = "(--|-)";
82 $autoabbrev = 0; # no automatic abbrev of options
83 $bundling = 0; # no bundling of single letter switches
84 $getopt_compat = 0; # disallow '+' to start options
85 $order = $REQUIRE_ORDER;
88 $genprefix = "(--|-|\\+)";
89 $autoabbrev = 1; # automatic abbrev of options
90 $bundling = 0; # bundling off by default
91 $getopt_compat = 1; # allow '+' to start options
94 # Other configurable settings.
95 $debug = 0; # for debugging
96 $error = 0; # error tally
97 $ignorecase = 1; # ignore case when matching options
98 $passthrough = 0; # leave unrecognized options alone
99 $gnu_compat = 0; # require --opt=val if value is optional
104 my $pkg = shift; # package
105 my @syms = (); # symbols to import
106 my @config = (); # configuration
107 my $dest = \@syms; # symbols first
109 if ( $_ eq ':config' ) {
110 $dest = \@config; # config next
113 push (@$dest, $_); # push
115 # Hide one level and call super.
116 local $Exporter::ExportLevel = 1;
117 $pkg->SUPER::import(@syms);
119 Configure (@config) if @config;
122 ################ Initialization ################
124 # Values for $order. See GNU getopt.c for details.
125 ($REQUIRE_ORDER, $PERMUTE, $RETURN_IN_ORDER) = (0..2);
126 # Version major/minor numbers.
127 ($major_version, $minor_version) = $VERSION =~ /^(\d+)\.(\d+)/;
131 ################ OO Interface ################
133 package Getopt::Long::Parser;
135 # NOTE: The object oriented routines use $error for thread locking.
137 lock ($Getopt::Long::error) if $] >= 5.005
140 # Store a copy of the default configuration. Since ConfigDefaults has
141 # just been called, what we get from Configure is the default.
142 my $default_config = do {
144 Getopt::Long::Configure ()
149 my $class = ref($that) || $that;
152 # Register the callers package.
153 my $self = { caller_pkg => (caller)[0] };
155 bless ($self, $class);
157 # Process config attributes.
158 if ( defined $atts{config} ) {
160 my $save = Getopt::Long::Configure ($default_config, @{$atts{config}});
161 $self->{settings} = Getopt::Long::Configure ($save);
162 delete ($atts{config});
164 # Else use default config.
166 $self->{settings} = $default_config;
169 if ( %atts ) { # Oops
170 die(__PACKAGE__.": unhandled attributes: ".
171 join(" ", sort(keys(%atts)))."\n");
182 # Restore settings, merge new settings in.
183 my $save = Getopt::Long::Configure ($self->{settings}, @_);
185 # Restore orig config and save the new config.
186 $self->{settings} = Configure ($save);
194 # Restore config settings.
195 my $save = Getopt::Long::Configure ($self->{settings});
199 $Getopt::Long::caller = $self->{caller_pkg};
202 # Locally set exception handler to default, otherwise it will
203 # be called implicitly here, and again explicitly when we try
204 # to deliver the messages.
205 local ($SIG{__DIE__}) = '__DEFAULT__';
206 $ret = Getopt::Long::GetOptions (@_);
209 # Restore saved settings.
210 Getopt::Long::Configure ($save);
212 # Handle errors and return value.
217 package Getopt::Long;
219 # Indices in option control info.
220 # Note that ParseOptions uses the fields directly. Search for 'hard-wired'.
221 use constant CTL_TYPE => 0;
222 #use constant CTL_TYPE_FLAG => '';
223 #use constant CTL_TYPE_NEG => '!';
224 #use constant CTL_TYPE_INCR => '+';
225 #use constant CTL_TYPE_INT => 'i';
226 #use constant CTL_TYPE_INTINC => 'I';
227 #use constant CTL_TYPE_XINT => 'o';
228 #use constant CTL_TYPE_FLOAT => 'f';
229 #use constant CTL_TYPE_STRING => 's';
231 use constant CTL_CNAME => 1;
233 use constant CTL_MAND => 2;
235 use constant CTL_DEST => 3;
236 use constant CTL_DEST_SCALAR => 0;
237 use constant CTL_DEST_ARRAY => 1;
238 use constant CTL_DEST_HASH => 2;
239 use constant CTL_DEST_CODE => 3;
241 use constant CTL_DEFAULT => 4;
244 #use constant CTL_RANGE => ;
245 #use constant CTL_REPEAT => ;
249 my @optionlist = @_; # local copy of the option descriptions
250 my $argend = '--'; # option list terminator
251 my %opctl = (); # table of option specs
252 my $pkg = $caller || (caller)[0]; # current context
253 # Needed if linkage is omitted.
254 my @ret = (); # accum for non-options
255 my %linkage; # linkage
256 my $userlinkage; # user supplied HASH
257 my $opt; # current option
258 my $prefix = $genprefix; # current prefix
262 print STDERR ("GetOpt::Long $Getopt::Long::VERSION (",
263 '$Revision: 2.55 $', ") ",
264 "called from package \"$pkg\".",
268 "autoabbrev=$autoabbrev,".
269 "bundling=$bundling,",
270 "getopt_compat=$getopt_compat,",
271 "gnu_compat=$gnu_compat,",
274 "ignorecase=$ignorecase,",
275 "passthrough=$passthrough,",
276 "genprefix=\"$genprefix\".",
280 # Check for ref HASH as first argument.
281 # First argument may be an object. It's OK to use this as long
282 # as it is really a hash underneath.
283 $userlinkage = undef;
284 if ( @optionlist && ref($optionlist[0]) and
285 "$optionlist[0]" =~ /^(?:.*\=)?HASH\([^\(]*\)$/ ) {
286 $userlinkage = shift (@optionlist);
287 print STDERR ("=> user linkage: $userlinkage\n") if $debug;
290 # See if the first element of the optionlist contains option
291 # starter characters.
292 # Be careful not to interpret '<>' as option starters.
293 if ( @optionlist && $optionlist[0] =~ /^\W+$/
294 && !($optionlist[0] eq '<>'
296 && ref($optionlist[1])) ) {
297 $prefix = shift (@optionlist);
298 # Turn into regexp. Needs to be parenthesized!
299 $prefix =~ s/(\W)/\\$1/g;
300 $prefix = "([" . $prefix . "])";
301 print STDERR ("=> prefix=\"$prefix\"\n") if $debug;
304 # Verify correctness of optionlist.
306 while ( @optionlist ) {
307 my $opt = shift (@optionlist);
309 # Strip leading prefix so people can specify "--foo=i" if they like.
310 $opt = $+ if $opt =~ /^$prefix+(.*)$/s;
312 if ( $opt eq '<>' ) {
313 if ( (defined $userlinkage)
314 && !(@optionlist > 0 && ref($optionlist[0]))
315 && (exists $userlinkage->{$opt})
316 && ref($userlinkage->{$opt}) ) {
317 unshift (@optionlist, $userlinkage->{$opt});
319 unless ( @optionlist > 0
320 && ref($optionlist[0]) && ref($optionlist[0]) eq 'CODE' ) {
321 $error .= "Option spec <> requires a reference to a subroutine\n";
322 # Kill the linkage (to avoid another error).
324 if @optionlist && ref($optionlist[0]);
327 $linkage{'<>'} = shift (@optionlist);
332 my ($name, $orig) = ParseOptionSpec ($opt, \%opctl);
333 unless ( defined $name ) {
334 # Failed. $orig contains the error message. Sorry for the abuse.
336 # Kill the linkage (to avoid another error).
338 if @optionlist && ref($optionlist[0]);
342 # If no linkage is supplied in the @optionlist, copy it from
343 # the userlinkage if available.
344 if ( defined $userlinkage ) {
345 unless ( @optionlist > 0 && ref($optionlist[0]) ) {
346 if ( exists $userlinkage->{$orig} &&
347 ref($userlinkage->{$orig}) ) {
348 print STDERR ("=> found userlinkage for \"$orig\": ",
349 "$userlinkage->{$orig}\n")
351 unshift (@optionlist, $userlinkage->{$orig});
354 # Do nothing. Being undefined will be handled later.
360 # Copy the linkage. If omitted, link to global variable.
361 if ( @optionlist > 0 && ref($optionlist[0]) ) {
362 print STDERR ("=> link \"$orig\" to $optionlist[0]\n")
364 my $rl = ref($linkage{$orig} = shift (@optionlist));
366 if ( $rl eq "ARRAY" ) {
367 $opctl{$name}[CTL_DEST] = CTL_DEST_ARRAY;
369 elsif ( $rl eq "HASH" ) {
370 $opctl{$name}[CTL_DEST] = CTL_DEST_HASH;
372 elsif ( $rl eq "SCALAR" || $rl eq "CODE" ) {
376 $error .= "Invalid option linkage for \"$opt\"\n";
380 # Link to global $opt_XXX variable.
381 # Make sure a valid perl identifier results.
384 if ( $opctl{$name}[CTL_DEST] == CTL_DEST_ARRAY ) {
385 print STDERR ("=> link \"$orig\" to \@$pkg","::opt_$ov\n")
387 eval ("\$linkage{\$orig} = \\\@".$pkg."::opt_$ov;");
389 elsif ( $opctl{$name}[CTL_DEST] == CTL_DEST_HASH ) {
390 print STDERR ("=> link \"$orig\" to \%$pkg","::opt_$ov\n")
392 eval ("\$linkage{\$orig} = \\\%".$pkg."::opt_$ov;");
395 print STDERR ("=> link \"$orig\" to \$$pkg","::opt_$ov\n")
397 eval ("\$linkage{\$orig} = \\\$".$pkg."::opt_$ov;");
402 # Bail out if errors found.
403 die ($error) if $error;
406 # Show the options tables if debugging.
410 while ( ($k,$v) = each(%opctl) ) {
411 print STDERR ($arrow, "\$opctl{$k} = $v ", OptCtl($v), "\n");
416 # Process argument list
418 while ( $goon && @ARGV > 0 ) {
421 $opt = shift (@ARGV);
422 print STDERR ("=> arg \"", $opt, "\"\n") if $debug;
424 # Double dash is option list terminator.
425 last if $opt eq $argend;
429 my $found; # success status
430 my $key; # key (if hash type)
431 my $arg; # option argument
432 my $ctl; # the opctl entry
434 ($found, $opt, $ctl, $arg, $key) =
435 FindOption ($prefix, $argend, $opt, \%opctl);
439 # FindOption undefines $opt in case of errors.
440 next unless defined $opt;
442 if ( defined $arg ) {
444 # Get the canonical name.
445 print STDERR ("=> cname for \"$opt\" is ") if $debug;
446 $opt = $ctl->[CTL_CNAME];
447 print STDERR ("\"$ctl->[CTL_CNAME]\"\n") if $debug;
449 if ( defined $linkage{$opt} ) {
450 print STDERR ("=> ref(\$L{$opt}) -> ",
451 ref($linkage{$opt}), "\n") if $debug;
453 if ( ref($linkage{$opt}) eq 'SCALAR' ) {
454 if ( $ctl->[CTL_TYPE] eq '+' ) {
455 print STDERR ("=> \$\$L{$opt} += \"$arg\"\n")
457 if ( defined ${$linkage{$opt}} ) {
458 ${$linkage{$opt}} += $arg;
461 ${$linkage{$opt}} = $arg;
465 print STDERR ("=> \$\$L{$opt} = \"$arg\"\n")
467 ${$linkage{$opt}} = $arg;
470 elsif ( ref($linkage{$opt}) eq 'ARRAY' ) {
471 print STDERR ("=> push(\@{\$L{$opt}, \"$arg\")\n")
473 push (@{$linkage{$opt}}, $arg);
475 elsif ( ref($linkage{$opt}) eq 'HASH' ) {
476 print STDERR ("=> \$\$L{$opt}->{$key} = \"$arg\"\n")
478 $linkage{$opt}->{$key} = $arg;
480 elsif ( ref($linkage{$opt}) eq 'CODE' ) {
481 print STDERR ("=> &L{$opt}(\"$opt\"",
482 $ctl->[CTL_DEST] == CTL_DEST_HASH ? ", \"$key\"" : "",
487 local $SIG{__DIE__} = '__DEFAULT__';
488 &{$linkage{$opt}}($opt,
489 $ctl->[CTL_DEST] == CTL_DEST_HASH ? ($key) : (),
492 print STDERR ("=> die($@)\n") if $debug && $@ ne '';
494 if ( $@ =~ /^!FINISH\b/ ) {
504 print STDERR ("Invalid REF type \"", ref($linkage{$opt}),
506 die("Getopt::Long -- internal error!\n");
509 # No entry in linkage means entry in userlinkage.
510 elsif ( $ctl->[CTL_DEST] == CTL_DEST_ARRAY ) {
511 if ( defined $userlinkage->{$opt} ) {
512 print STDERR ("=> push(\@{\$L{$opt}}, \"$arg\")\n")
514 push (@{$userlinkage->{$opt}}, $arg);
517 print STDERR ("=>\$L{$opt} = [\"$arg\"]\n")
519 $userlinkage->{$opt} = [$arg];
522 elsif ( $ctl->[CTL_DEST] == CTL_DEST_HASH ) {
523 if ( defined $userlinkage->{$opt} ) {
524 print STDERR ("=> \$L{$opt}->{$key} = \"$arg\"\n")
526 $userlinkage->{$opt}->{$key} = $arg;
529 print STDERR ("=>\$L{$opt} = {$key => \"$arg\"}\n")
531 $userlinkage->{$opt} = {$key => $arg};
535 if ( $ctl->[CTL_TYPE] eq '+' ) {
536 print STDERR ("=> \$L{$opt} += \"$arg\"\n")
538 if ( defined $userlinkage->{$opt} ) {
539 $userlinkage->{$opt} += $arg;
542 $userlinkage->{$opt} = $arg;
546 print STDERR ("=>\$L{$opt} = \"$arg\"\n") if $debug;
547 $userlinkage->{$opt} = $arg;
553 # Not an option. Save it if we $PERMUTE and don't have a <>.
554 elsif ( $order == $PERMUTE ) {
555 # Try non-options call-back.
557 if ( (defined ($cb = $linkage{'<>'})) ) {
559 print STDERR ("=> &L{$tryopt}(\"$tryopt\")\n")
562 local $SIG{__DIE__} = '__DEFAULT__';
565 print STDERR ("=> die($@)\n") if $debug && $@ ne '';
567 if ( $@ =~ /^!FINISH\b/ ) {
577 print STDERR ("=> saving \"$tryopt\" ",
578 "(not an option, may permute)\n") if $debug;
579 push (@ret, $tryopt);
584 # ...otherwise, terminate.
586 # Push this one back and exit.
587 unshift (@ARGV, $tryopt);
588 return ($error == 0);
594 if ( @ret && $order == $PERMUTE ) {
595 # Push back accumulated arguments
596 print STDERR ("=> restoring \"", join('" "', @ret), "\"\n")
598 unshift (@ARGV, @ret);
601 return ($error == 0);
604 # A readable representation of what's in an optbl.
607 my @v = map { defined($_) ? ($_) : ("<undef>") } @$v;
612 $v[CTL_MAND] ? "O" : "M",
613 ("\$","\@","\%","\&")[$v[CTL_DEST] || 0],
614 "\"$v[CTL_DEFAULT]\"",
615 # $v[CTL_RANGE] || '',
616 # $v[CTL_REPEAT] || '',
620 # Parse an option specification and fill the tables.
621 sub ParseOptionSpec ($$) {
622 my ($opt, $opctl) = @_;
629 # Alias names, or "?"
630 (?: \| (?: \? | \w[-\w]* )? )*
633 # Either modifiers ...
636 # ... or a value/dest specification
639 # ... or an optional-with-default spec
640 : (?: -?\d+ | \+ ) [@%]?
643 return (undef, "Error in option spec: \"$opt\"\n");
646 my ($names, $spec) = ($1, $2);
647 $spec = '' unless defined $spec;
649 # $orig keeps track of the primary name the user specified.
650 # This name will be used for the internal or external linkage.
651 # In other words, if the user specifies "FoO|BaR", it will
652 # match any case combinations of 'foo' and 'bar', but if a global
653 # variable needs to be set, it will be $opt_FoO in the exact case
658 if ( defined $names ) {
659 @names = split (/\|/, $names);
667 # Construct the opctl entries.
669 if ( $spec eq '' || $spec eq '+' || $spec eq '!' ) {
670 # Fields are hard-wired here.
671 $entry = [$spec,$orig,0,CTL_DEST_SCALAR,undef];
673 elsif ( $spec =~ /:(-?\d+|\+)([@%])?/ ) {
676 my $type = $def eq '+' ? 'I' : 'i';
678 $dest = $dest eq '@' ? CTL_DEST_ARRAY
679 : $dest eq '%' ? CTL_DEST_HASH : CTL_DEST_SCALAR;
680 # Fields are hard-wired here.
681 $entry = [$type,$orig,0,$dest,$def eq '+' ? undef : $def];
684 my ($mand, $type, $dest) = $spec =~ /([=:])([ionfs])([@%])?/;
685 $type = 'i' if $type eq 'n';
687 $dest = $dest eq '@' ? CTL_DEST_ARRAY
688 : $dest eq '%' ? CTL_DEST_HASH : CTL_DEST_SCALAR;
689 # Fields are hard-wired here.
690 $entry = [$type,$orig,$mand eq '=',$dest,undef];
693 # Process all names. First is canonical, the rest are aliases.
698 if $ignorecase > (($bundling && length($_) == 1) ? 1 : 0);
700 if ( exists $opctl->{$_} ) {
701 $dups .= "Duplicate specification \"$opt\" for option \"$_\"\n";
704 if ( $spec eq '!' ) {
705 $opctl->{"no$_"} = $entry;
706 $opctl->{$_} = [@$entry];
707 $opctl->{$_}->[CTL_TYPE] = '';
710 $opctl->{$_} = $entry;
714 if ( $dups && $^W ) {
715 foreach ( split(/\n+/, $dups) ) {
723 sub FindOption ($$$$) {
725 # returns (1, $opt, $ctl, $arg, $key) if okay,
726 # returns (1, undef) if option in error,
727 # returns (0) otherwise.
729 my ($prefix, $argend, $opt, $opctl) = @_;
731 print STDERR ("=> find \"$opt\"\n") if $debug;
733 return (0) unless $opt =~ /^$prefix(.*)$/s;
734 return (0) if $opt eq "-" && !defined $opctl->{''};
739 print STDERR ("=> split \"$starter\"+\"$opt\"\n") if $debug;
741 my $optarg; # value supplied with --opt=value
742 my $rest; # remainder from unbundling
744 # If it is a long option, it may include the value.
745 # With getopt_compat, only if not bundling.
746 if ( ($starter eq "--"
747 || ($getopt_compat && ($bundling == 0 || $bundling == 2)))
748 && $opt =~ /^([^=]+)=(.*)$/s ) {
751 print STDERR ("=> option \"", $opt,
752 "\", optarg = \"$optarg\"\n") if $debug;
757 my $tryopt = $opt; # option to try
759 if ( $bundling && $starter eq '-' ) {
761 # To try overrides, obey case ignore.
762 $tryopt = $ignorecase ? lc($opt) : $opt;
764 # If bundling == 2, long options can override bundles.
765 if ( $bundling == 2 && length($tryopt) > 1
766 && defined ($opctl->{$tryopt}) ) {
767 print STDERR ("=> $starter$tryopt overrides unbundling\n")
772 # Unbundle single letter option.
773 $rest = length ($tryopt) > 0 ? substr ($tryopt, 1) : '';
774 $tryopt = substr ($tryopt, 0, 1);
775 $tryopt = lc ($tryopt) if $ignorecase > 1;
776 print STDERR ("=> $starter$tryopt unbundled from ",
777 "$starter$tryopt$rest\n") if $debug;
778 $rest = undef unless $rest ne '';
782 # Try auto-abbreviation.
783 elsif ( $autoabbrev ) {
784 # Sort the possible long option names.
785 my @names = sort(keys (%$opctl));
786 # Downcase if allowed.
787 $opt = lc ($opt) if $ignorecase;
789 # Turn option name into pattern.
790 my $pat = quotemeta ($opt);
791 # Look up in option names.
792 my @hits = grep (/^$pat/, @names);
793 print STDERR ("=> ", scalar(@hits), " hits (@hits) with \"$pat\" ",
794 "out of ", scalar(@names), "\n") if $debug;
796 # Check for ambiguous results.
797 unless ( (@hits <= 1) || (grep ($_ eq $opt, @hits) == 1) ) {
798 # See if all matches are for the same option.
801 $_ = $opctl->{$_}->[CTL_CNAME]
802 if defined $opctl->{$_}->[CTL_CNAME];
805 # Now see if it really is ambiguous.
806 unless ( keys(%hit) == 1 ) {
807 return (0) if $passthrough;
808 warn ("Option ", $opt, " is ambiguous (",
809 join(", ", @hits), ")\n");
816 # Complete the option name, if appropriate.
817 if ( @hits == 1 && $hits[0] ne $opt ) {
819 $tryopt = lc ($tryopt) if $ignorecase;
820 print STDERR ("=> option \"$opt\" -> \"$tryopt\"\n")
825 # Map to all lowercase if ignoring case.
826 elsif ( $ignorecase ) {
830 # Check validity by fetching the info.
831 my $ctl = $opctl->{$tryopt};
832 unless ( defined $ctl ) {
833 return (0) if $passthrough;
834 warn ("Unknown option: ", $opt, "\n");
840 print STDERR ("=> found ", OptCtl($ctl),
841 " for \"", $opt, "\"\n") if $debug;
843 #### Determine argument status ####
845 # If it is an option w/o argument, we're almost finished with it.
846 my $type = $ctl->[CTL_TYPE];
849 if ( $type eq '' || $type eq '!' || $type eq '+' ) {
850 if ( defined $optarg ) {
851 return (0) if $passthrough;
852 warn ("Option ", $opt, " does not take an argument\n");
856 elsif ( $type eq '' || $type eq '+' ) {
857 # Supply explicit value.
861 $opt =~ s/^no//i; # strip NO prefix
862 $arg = 0; # supply explicit value
864 unshift (@ARGV, $starter.$rest) if defined $rest;
865 return (1, $opt, $ctl, $arg);
868 # Get mandatory status and type info.
869 my $mand = $ctl->[CTL_MAND];
871 # Check if there is an option argument available.
872 if ( $gnu_compat && defined $optarg && $optarg eq '' ) {
873 return (1, $opt, $ctl, $type eq 's' ? '' : 0) unless $mand;
874 $optarg = 0 unless $type eq 's';
877 # Check if there is an option argument available.
880 : !(defined $rest || @ARGV > 0) ) {
881 # Complain if this option needs an argument.
883 return (0) if $passthrough;
884 warn ("Option ", $opt, " requires an argument\n");
888 if ( $type eq 'I' ) {
889 # Fake incremental type.
892 return (1, $opt, \@c, 1);
894 return (1, $opt, $ctl,
895 defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] :
896 $type eq 's' ? '' : 0);
899 # Get (possibly optional) argument.
900 $arg = (defined $rest ? $rest
901 : (defined $optarg ? $optarg : shift (@ARGV)));
903 # Get key if this is a "name=value" pair for a hash option.
905 if ($ctl->[CTL_DEST] == CTL_DEST_HASH && defined $arg) {
906 ($key, $arg) = ($arg =~ /^([^=]*)=(.*)$/s) ? ($1, $2) : ($arg, 1);
909 #### Check if the argument is valid for this option ####
911 if ( $type eq 's' ) { # string
912 # A mandatory string takes anything.
913 return (1, $opt, $ctl, $arg, $key) if $mand;
915 # An optional string takes almost anything.
916 return (1, $opt, $ctl, $arg, $key)
917 if defined $optarg || defined $rest;
918 return (1, $opt, $ctl, $arg, $key) if $arg eq "-"; # ??
920 # Check for option or option list terminator.
921 if ($arg eq $argend ||
922 $arg =~ /^$prefix.+/) {
924 unshift (@ARGV, $arg);
925 # Supply empty value.
930 elsif ( $type eq 'i' # numeric/integer
931 || $type eq 'I' # numeric/integer w/ incr default
932 || $type eq 'o' ) { # dec/oct/hex/bin value
935 $type eq 'o' ? "[-+]?[1-9][0-9]*|0x[0-9a-f]+|0b[01]+|0[0-7]*"
938 if ( $bundling && defined $rest && $rest =~ /^($o_valid)(.*)$/si ) {
941 $arg = ($type eq 'o' && $arg =~ /^0/) ? oct($arg) : 0+$arg;
942 unshift (@ARGV, $starter.$rest) if defined $rest && $rest ne '';
944 elsif ( $arg =~ /^($o_valid)$/si ) {
945 $arg = ($type eq 'o' && $arg =~ /^0/) ? oct($arg) : 0+$arg;
948 if ( defined $optarg || $mand ) {
949 if ( $passthrough ) {
950 unshift (@ARGV, defined $rest ? $starter.$rest : $arg)
951 unless defined $optarg;
954 warn ("Value \"", $arg, "\" invalid for option ",
956 $type eq 'o' ? "extended " : '',
957 "number expected)\n");
960 unshift (@ARGV, $starter.$rest) if defined $rest;
965 unshift (@ARGV, defined $rest ? $starter.$rest : $arg);
966 if ( $type eq 'I' ) {
967 # Fake incremental type.
970 return (1, $opt, \@c, 1);
972 # Supply default value.
973 $arg = defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] : 0;
978 elsif ( $type eq 'f' ) { # real number, int is also ok
979 # We require at least one digit before a point or 'e',
980 # and at least one digit following the point and 'e'.
982 if ( $bundling && defined $rest &&
983 $rest =~ /^([-+]?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?)(.*)$/s ) {
986 unshift (@ARGV, $starter.$rest) if defined $rest && $rest ne '';
988 elsif ( $arg !~ /^[-+]?[0-9.]+(\.[0-9]+)?([eE][-+]?[0-9]+)?$/ ) {
989 if ( defined $optarg || $mand ) {
990 if ( $passthrough ) {
991 unshift (@ARGV, defined $rest ? $starter.$rest : $arg)
992 unless defined $optarg;
995 warn ("Value \"", $arg, "\" invalid for option ",
996 $opt, " (real number expected)\n");
999 unshift (@ARGV, $starter.$rest) if defined $rest;
1004 unshift (@ARGV, defined $rest ? $starter.$rest : $arg);
1005 # Supply default value.
1011 die("GetOpt::Long internal error (Can't happen)\n");
1013 return (1, $opt, $ctl, $arg, $key);
1016 # Getopt::Long Configuration.
1021 [ $error, $debug, $major_version, $minor_version,
1022 $autoabbrev, $getopt_compat, $ignorecase, $bundling, $order,
1023 $gnu_compat, $passthrough, $genprefix ];
1025 if ( ref($options[0]) eq 'ARRAY' ) {
1026 ( $error, $debug, $major_version, $minor_version,
1027 $autoabbrev, $getopt_compat, $ignorecase, $bundling, $order,
1028 $gnu_compat, $passthrough, $genprefix ) = @{shift(@options)};
1032 foreach $opt ( @options ) {
1033 my $try = lc ($opt);
1035 if ( $try =~ /^no_?(.*)$/s ) {
1039 if ( ($try eq 'default' or $try eq 'defaults') && $action ) {
1042 elsif ( ($try eq 'posix_default' or $try eq 'posix_defaults') ) {
1043 local $ENV{POSIXLY_CORRECT};
1044 $ENV{POSIXLY_CORRECT} = 1 if $action;
1047 elsif ( $try eq 'auto_abbrev' or $try eq 'autoabbrev' ) {
1048 $autoabbrev = $action;
1050 elsif ( $try eq 'getopt_compat' ) {
1051 $getopt_compat = $action;
1053 elsif ( $try eq 'gnu_getopt' ) {
1061 elsif ( $try eq 'gnu_compat' ) {
1062 $gnu_compat = $action;
1064 elsif ( $try eq 'ignorecase' or $try eq 'ignore_case' ) {
1065 $ignorecase = $action;
1067 elsif ( $try eq 'ignore_case_always' ) {
1068 $ignorecase = $action ? 2 : 0;
1070 elsif ( $try eq 'bundling' ) {
1071 $bundling = $action;
1073 elsif ( $try eq 'bundling_override' ) {
1074 $bundling = $action ? 2 : 0;
1076 elsif ( $try eq 'require_order' ) {
1077 $order = $action ? $REQUIRE_ORDER : $PERMUTE;
1079 elsif ( $try eq 'permute' ) {
1080 $order = $action ? $PERMUTE : $REQUIRE_ORDER;
1082 elsif ( $try eq 'pass_through' or $try eq 'passthrough' ) {
1083 $passthrough = $action;
1085 elsif ( $try =~ /^prefix=(.+)$/ && $action ) {
1087 # Turn into regexp. Needs to be parenthesized!
1088 $genprefix = "(" . quotemeta($genprefix) . ")";
1089 eval { '' =~ /$genprefix/; };
1090 die("Getopt::Long: invalid pattern \"$genprefix\"") if $@;
1092 elsif ( $try =~ /^prefix_pattern=(.+)$/ && $action ) {
1094 # Parenthesize if needed.
1095 $genprefix = "(" . $genprefix . ")"
1096 unless $genprefix =~ /^\(.*\)$/;
1097 eval { '' =~ /$genprefix/; };
1098 die("Getopt::Long: invalid pattern \"$genprefix\"") if $@;
1100 elsif ( $try eq 'debug' ) {
1104 die("Getopt::Long: unknown config parameter \"$opt\"")
1115 ################ Documentation ################
1119 Getopt::Long - Extended processing of command line options
1124 my $data = "file.dat";
1127 $result = GetOptions ("length=i" => \$length, # numeric
1128 "file=s" => \$data, # string
1129 "verbose" => \$verbose); # flag
1133 The Getopt::Long module implements an extended getopt function called
1134 GetOptions(). This function adheres to the POSIX syntax for command
1135 line options, with GNU extensions. In general, this means that options
1136 have long names instead of single letters, and are introduced with a
1137 double dash "--". Support for bundling of command line options, as was
1138 the case with the more traditional single-letter approach, is provided
1139 but not enabled by default.
1141 =head1 Command Line Options, an Introduction
1143 Command line operated programs traditionally take their arguments from
1144 the command line, for example filenames or other information that the
1145 program needs to know. Besides arguments, these programs often take
1146 command line I<options> as well. Options are not necessary for the
1147 program to work, hence the name 'option', but are used to modify its
1148 default behaviour. For example, a program could do its job quietly,
1149 but with a suitable option it could provide verbose information about
1152 Command line options come in several flavours. Historically, they are
1153 preceded by a single dash C<->, and consist of a single letter.
1157 Usually, these single-character options can be bundled:
1161 Options can have values, the value is placed after the option
1162 character. Sometimes with whitespace in between, sometimes not:
1166 Due to the very cryptic nature of these options, another style was
1167 developed that used long names. So instead of a cryptic C<-l> one
1168 could use the more descriptive C<--long>. To distinguish between a
1169 bundle of single-character options and a long one, two dashes are used
1170 to precede the option name. Early implementations of long options used
1171 a plus C<+> instead. Also, option values could be specified either
1180 The C<+> form is now obsolete and strongly deprecated.
1182 =head1 Getting Started with Getopt::Long
1184 Getopt::Long is the Perl5 successor of C<newgetopt.pl>. This was
1185 the first Perl module that provided support for handling the new style
1186 of command line options, hence the name Getopt::Long. This module
1187 also supports single-character options and bundling. In this case, the
1188 options are restricted to alphabetic characters only, and the
1189 characters C<?> and C<->.
1191 To use Getopt::Long from a Perl program, you must include the
1192 following line in your Perl program:
1196 This will load the core of the Getopt::Long module and prepare your
1197 program for using it. Most of the actual Getopt::Long code is not
1198 loaded until you really call one of its functions.
1200 In the default configuration, options names may be abbreviated to
1201 uniqueness, case does not matter, and a single dash is sufficient,
1202 even for long option names. Also, options may be placed between
1203 non-option arguments. See L<Configuring Getopt::Long> for more
1204 details on how to configure Getopt::Long.
1206 =head2 Simple options
1208 The most simple options are the ones that take no values. Their mere
1209 presence on the command line enables the option. Popular examples are:
1211 --all --verbose --quiet --debug
1213 Handling simple options is straightforward:
1215 my $verbose = ''; # option variable with default value (false)
1216 my $all = ''; # option variable with default value (false)
1217 GetOptions ('verbose' => \$verbose, 'all' => \$all);
1219 The call to GetOptions() parses the command line arguments that are
1220 present in C<@ARGV> and sets the option variable to the value C<1> if
1221 the option did occur on the command line. Otherwise, the option
1222 variable is not touched. Setting the option value to true is often
1223 called I<enabling> the option.
1225 The option name as specified to the GetOptions() function is called
1226 the option I<specification>. Later we'll see that this specification
1227 can contain more than just the option name. The reference to the
1228 variable is called the option I<destination>.
1230 GetOptions() will return a true value if the command line could be
1231 processed successfully. Otherwise, it will write error messages to
1232 STDERR, and return a false result.
1234 =head2 A little bit less simple options
1236 Getopt::Long supports two useful variants of simple options:
1237 I<negatable> options and I<incremental> options.
1239 A negatable option is specified with an exclamation mark C<!> after the
1242 my $verbose = ''; # option variable with default value (false)
1243 GetOptions ('verbose!' => \$verbose);
1245 Now, using C<--verbose> on the command line will enable C<$verbose>,
1246 as expected. But it is also allowed to use C<--noverbose>, which will
1247 disable C<$verbose> by setting its value to C<0>. Using a suitable
1248 default value, the program can find out whether C<$verbose> is false
1249 by default, or disabled by using C<--noverbose>.
1251 An incremental option is specified with a plus C<+> after the
1254 my $verbose = ''; # option variable with default value (false)
1255 GetOptions ('verbose+' => \$verbose);
1257 Using C<--verbose> on the command line will increment the value of
1258 C<$verbose>. This way the program can keep track of how many times the
1259 option occurred on the command line. For example, each occurrence of
1260 C<--verbose> could increase the verbosity level of the program.
1262 =head2 Mixing command line option with other arguments
1264 Usually programs take command line options as well as other arguments,
1265 for example, file names. It is good practice to always specify the
1266 options first, and the other arguments last. Getopt::Long will,
1267 however, allow the options and arguments to be mixed and 'filter out'
1268 all the options before passing the rest of the arguments to the
1269 program. To stop Getopt::Long from processing further arguments,
1270 insert a double dash C<--> on the command line:
1274 In this example, C<--all> will I<not> be treated as an option, but
1275 passed to the program unharmed, in C<@ARGV>.
1277 =head2 Options with values
1279 For options that take values it must be specified whether the option
1280 value is required or not, and what kind of value the option expects.
1282 Three kinds of values are supported: integer numbers, floating point
1283 numbers, and strings.
1285 If the option value is required, Getopt::Long will take the
1286 command line argument that follows the option and assign this to the
1287 option variable. If, however, the option value is specified as
1288 optional, this will only be done if that value does not look like a
1289 valid command line option itself.
1291 my $tag = ''; # option variable with default value
1292 GetOptions ('tag=s' => \$tag);
1294 In the option specification, the option name is followed by an equals
1295 sign C<=> and the letter C<s>. The equals sign indicates that this
1296 option requires a value. The letter C<s> indicates that this value is
1297 an arbitrary string. Other possible value types are C<i> for integer
1298 values, and C<f> for floating point values. Using a colon C<:> instead
1299 of the equals sign indicates that the option value is optional. In
1300 this case, if no suitable value is supplied, string valued options get
1301 an empty string C<''> assigned, while numeric options are set to C<0>.
1303 =head2 Options with multiple values
1305 Options sometimes take several values. For example, a program could
1306 use multiple directories to search for library files:
1308 --library lib/stdlib --library lib/extlib
1310 To accomplish this behaviour, simply specify an array reference as the
1311 destination for the option:
1314 GetOptions ("library=s" => \@libfiles);
1316 Used with the example above, C<@libfiles> would contain two strings
1317 upon completion: C<"lib/srdlib"> and C<"lib/extlib">, in that order.
1318 It is also possible to specify that only integer or floating point
1319 numbers are acceptible values.
1321 Often it is useful to allow comma-separated lists of values as well as
1322 multiple occurrences of the options. This is easy using Perl's split()
1323 and join() operators:
1326 GetOptions ("library=s" => \@libfiles);
1327 @libfiles = split(/,/,join(',',@libfiles));
1329 Of course, it is important to choose the right separator string for
1332 =head2 Options with hash values
1334 If the option destination is a reference to a hash, the option will
1335 take, as value, strings of the form I<key>C<=>I<value>. The value will
1336 be stored with the specified key in the hash.
1339 GetOptions ("define=s" => \%defines);
1341 When used with command line options:
1343 --define os=linux --define vendor=redhat
1345 the hash C<%defines> will contain two keys, C<"os"> with value
1346 C<"linux> and C<"vendor"> with value C<"redhat">.
1347 It is also possible to specify that only integer or floating point
1348 numbers are acceptible values. The keys are always taken to be strings.
1350 =head2 User-defined subroutines to handle options
1352 Ultimate control over what should be done when (actually: each time)
1353 an option is encountered on the command line can be achieved by
1354 designating a reference to a subroutine (or an anonymous subroutine)
1355 as the option destination. When GetOptions() encounters the option, it
1356 will call the subroutine with two or three arguments. The first
1357 argument is the name of the option. For a scalar or array destination,
1358 the second argument is the value to be stored. For a hash destination,
1359 the second arguments is the key to the hash, and the third argument
1360 the value to be stored. It is up to the subroutine to store the value,
1361 or do whatever it thinks is appropriate.
1363 A trivial application of this mechanism is to implement options that
1364 are related to each other. For example:
1366 my $verbose = ''; # option variable with default value (false)
1367 GetOptions ('verbose' => \$verbose,
1368 'quiet' => sub { $verbose = 0 });
1370 Here C<--verbose> and C<--quiet> control the same variable
1371 C<$verbose>, but with opposite values.
1373 If the subroutine needs to signal an error, it should call die() with
1374 the desired error message as its argument. GetOptions() will catch the
1375 die(), issue the error message, and record that an error result must
1376 be returned upon completion.
1378 If the text of the error message starts with an exclamantion mark C<!>
1379 it is interpreted specially by GetOptions(). There is currently one
1380 special command implemented: C<die("!FINISH")> will cause GetOptions()
1381 to stop processing options, as if it encountered a double dash C<-->.
1383 =head2 Options with multiple names
1385 Often it is user friendly to supply alternate mnemonic names for
1386 options. For example C<--height> could be an alternate name for
1387 C<--length>. Alternate names can be included in the option
1388 specification, separated by vertical bar C<|> characters. To implement
1391 GetOptions ('length|height=f' => \$length);
1393 The first name is called the I<primary> name, the other names are
1396 Multiple alternate names are possible.
1398 =head2 Case and abbreviations
1400 Without additional configuration, GetOptions() will ignore the case of
1401 option names, and allow the options to be abbreviated to uniqueness.
1403 GetOptions ('length|height=f' => \$length, "head" => \$head);
1405 This call will allow C<--l> and C<--L> for the length option, but
1406 requires a least C<--hea> and C<--hei> for the head and height options.
1408 =head2 Summary of Option Specifications
1410 Each option specifier consists of two parts: the name specification
1411 and the argument specification.
1413 The name specification contains the name of the option, optionally
1414 followed by a list of alternative names separated by vertical bar
1417 length option name is "length"
1418 length|size|l name is "length", aliases are "size" and "l"
1420 The argument specification is optional. If omitted, the option is
1421 considered boolean, a value of 1 will be assigned when the option is
1422 used on the command line.
1424 The argument specification can be
1430 The option does not take an argument and may be negated, i.e. prefixed
1431 by "no". E.g. C<"foo!"> will allow C<--foo> (a value of 1 will be
1432 assigned) and C<--nofoo> (a value of 0 will be assigned). If the
1433 option has aliases, this applies to the aliases as well.
1435 Using negation on a single letter option when bundling is in effect is
1436 pointless and will result in a warning.
1440 The option does not take an argument and will be incremented by 1
1441 every time it appears on the command line. E.g. C<"more+">, when used
1442 with C<--more --more --more>, will increment the value three times,
1443 resulting in a value of 3 (provided it was 0 or undefined at first).
1445 The C<+> specifier is ignored if the option destination is not a scalar.
1447 =item = I<type> [ I<desttype> ]
1449 The option requires an argument of the given type. Supported types
1456 String. An arbitrary sequence of characters. It is valid for the
1457 argument to start with C<-> or C<-->.
1461 Integer. An optional leading plus or minus sign, followed by a
1466 Extended integer, Perl style. This can be either an optional leading
1467 plus or minus sign, followed by a sequence of digits, or an octal
1468 string (a zero, optionally followed by '0', '1', .. '7'), or a
1469 hexadecimal string (C<0x> followed by '0' .. '9', 'a' .. 'f', case
1470 insensitive), or a binary string (C<0b> followed by a series of '0'
1475 Real number. For example C<3.14>, C<-6.23E24> and so on.
1479 The I<desttype> can be C<@> or C<%> to specify that the option is
1480 list or a hash valued. This is only needed when the destination for
1481 the option value is not otherwise specified. It should be omitted when
1484 =item : I<type> [ I<desttype> ]
1486 Like C<=>, but designates the argument as optional.
1487 If omitted, an empty string will be assigned to string values options,
1488 and the value zero to numeric options.
1490 Note that if a string argument starts with C<-> or C<-->, it will be
1491 considered an option on itself.
1493 =item : I<number> [ I<desttype> ]
1495 Like C<:i>, but if the value is omitted, the I<number> will be assigned.
1497 =item : + [ I<desttype> ]
1499 Like C<:i>, but if the value is omitted, the current value for the
1500 option will be incremented.
1504 =head1 Advanced Possibilities
1506 =head2 Object oriented interface
1508 Getopt::Long can be used in an object oriented way as well:
1511 $p = new Getopt::Long::Parser;
1512 $p->configure(...configuration options...);
1513 if ($p->getoptions(...options descriptions...)) ...
1515 Configuration options can be passed to the constructor:
1517 $p = new Getopt::Long::Parser
1518 config => [...configuration options...];
1520 For thread safety, each method call will acquire an exclusive lock to
1521 the Getopt::Long module. So don't call these methods from a callback
1524 =head2 Documentation and help texts
1526 Getopt::Long encourages the use of Pod::Usage to produce help
1527 messages. For example:
1535 GetOptions('help|?' => \$help, man => \$man) or pod2usage(2);
1536 pod2usage(1) if $help;
1537 pod2usage(-exitstatus => 0, -verbose => 2) if $man;
1543 sample - Using GetOpt::Long and Pod::Usage
1547 sample [options] [file ...]
1550 -help brief help message
1551 -man full documentation
1559 Print a brief help message and exits.
1563 Prints the manual page and exits.
1569 B<This program> will read the given input file(s) and do someting
1570 useful with the contents thereof.
1574 See L<Pod::Usage> for details.
1576 =head2 Storing options in a hash
1578 Sometimes, for example when there are a lot of options, having a
1579 separate variable for each of them can be cumbersome. GetOptions()
1580 supports, as an alternative mechanism, storing options in a hash.
1582 To obtain this, a reference to a hash must be passed I<as the first
1583 argument> to GetOptions(). For each option that is specified on the
1584 command line, the option value will be stored in the hash with the
1585 option name as key. Options that are not actually used on the command
1586 line will not be put in the hash, on other words,
1587 C<exists($h{option})> (or defined()) can be used to test if an option
1588 was used. The drawback is that warnings will be issued if the program
1589 runs under C<use strict> and uses C<$h{option}> without testing with
1590 exists() or defined() first.
1593 GetOptions (\%h, 'length=i'); # will store in $h{length}
1595 For options that take list or hash values, it is necessary to indicate
1596 this by appending an C<@> or C<%> sign after the type:
1598 GetOptions (\%h, 'colours=s@'); # will push to @{$h{colours}}
1600 To make things more complicated, the hash may contain references to
1601 the actual destinations, for example:
1604 my %h = ('length' => \$len);
1605 GetOptions (\%h, 'length=i'); # will store in $len
1607 This example is fully equivalent with:
1610 GetOptions ('length=i' => \$len); # will store in $len
1612 Any mixture is possible. For example, the most frequently used options
1613 could be stored in variables while all other options get stored in the
1616 my $verbose = 0; # frequently referred
1617 my $debug = 0; # frequently referred
1618 my %h = ('verbose' => \$verbose, 'debug' => \$debug);
1619 GetOptions (\%h, 'verbose', 'debug', 'filter', 'size=i');
1620 if ( $verbose ) { ... }
1621 if ( exists $h{filter} ) { ... option 'filter' was specified ... }
1625 With bundling it is possible to set several single-character options
1626 at once. For example if C<a>, C<v> and C<x> are all valid options,
1630 would set all three.
1632 Getopt::Long supports two levels of bundling. To enable bundling, a
1633 call to Getopt::Long::Configure is required.
1635 The first level of bundling can be enabled with:
1637 Getopt::Long::Configure ("bundling");
1639 Configured this way, single-character options can be bundled but long
1640 options B<must> always start with a double dash C<--> to avoid
1641 abiguity. For example, when C<vax>, C<a>, C<v> and C<x> are all valid
1646 would set C<a>, C<v> and C<x>, but
1652 The second level of bundling lifts this restriction. It can be enabled
1655 Getopt::Long::Configure ("bundling_override");
1657 Now, C<-vax> would set the option C<vax>.
1659 When any level of bundling is enabled, option values may be inserted
1660 in the bundle. For example:
1668 When configured for bundling, single-character options are matched
1669 case sensitive while long options are matched case insensitive. To
1670 have the single-character options matched case insensitive as well,
1673 Getopt::Long::Configure ("bundling", "ignorecase_always");
1675 It goes without saying that bundling can be quite confusing.
1677 =head2 The lonesome dash
1679 Normally, a lone dash C<-> on the command line will not be considered
1680 an option. Option processing will terminate (unless "permute" is
1681 configured) and the dash will be left in C<@ARGV>.
1683 It is possible to get special treatment for a lone dash. This can be
1684 achieved by adding an option specification with an empty name, for
1687 GetOptions ('' => \$stdio);
1689 A lone dash on the command line will now be a legal option, and using
1690 it will set variable C<$stdio>.
1692 =head2 Argument callback
1694 A special option 'name' C<<>> can be used to designate a subroutine
1695 to handle non-option arguments. When GetOptions() encounters an
1696 argument that does not look like an option, it will immediately call this
1697 subroutine and passes it one parameter: the argument name.
1703 GetOptions ('width=i' => \$width, '<>' => \&process);
1705 When applied to the following command line:
1707 arg1 --width=72 arg2 --width=60 arg3
1710 C<process("arg1")> while C<$width> is C<80>,
1711 C<process("arg2")> while C<$width> is C<72>, and
1712 C<process("arg3")> while C<$width> is C<60>.
1714 This feature requires configuration option B<permute>, see section
1715 L<Configuring Getopt::Long>.
1718 =head1 Configuring Getopt::Long
1720 Getopt::Long can be configured by calling subroutine
1721 Getopt::Long::Configure(). This subroutine takes a list of quoted
1722 strings, each specifying a configuration option to be enabled, e.g.
1723 C<ignore_case>, or disabled, e.g. C<no_ignore_case>. Case does not
1724 matter. Multiple calls to Configure() are possible.
1726 Alternatively, as of version 2.24, the configuration options may be
1727 passed together with the C<use> statement:
1729 use Getopt::Long qw(:config no_ignore_case bundling);
1731 The following options are available:
1737 This option causes all configuration options to be reset to their
1742 This option causes all configuration options to be reset to their
1743 default values as if the environment variable POSIXLY_CORRECT had
1748 Allow option names to be abbreviated to uniqueness.
1749 Default is enabled unless environment variable
1750 POSIXLY_CORRECT has been set, in which case C<auto_abbrev> is disabled.
1754 Allow C<+> to start options.
1755 Default is enabled unless environment variable
1756 POSIXLY_CORRECT has been set, in which case C<getopt_compat> is disabled.
1760 C<gnu_compat> controls whether C<--opt=> is allowed, and what it should
1761 do. Without C<gnu_compat>, C<--opt=> gives an error. With C<gnu_compat>,
1762 C<--opt=> will give option C<opt> and empty value.
1763 This is the way GNU getopt_long() does it.
1767 This is a short way of setting C<gnu_compat> C<bundling> C<permute>
1768 C<no_getopt_compat>. With C<gnu_getopt>, command line handling should be
1769 fully compatible with GNU getopt_long().
1773 Whether command line arguments are allowed to be mixed with options.
1774 Default is disabled unless environment variable
1775 POSIXLY_CORRECT has been set, in which case C<require_order> is enabled.
1777 See also C<permute>, which is the opposite of C<require_order>.
1781 Whether command line arguments are allowed to be mixed with options.
1782 Default is enabled unless environment variable
1783 POSIXLY_CORRECT has been set, in which case C<permute> is disabled.
1784 Note that C<permute> is the opposite of C<require_order>.
1786 If C<permute> is enabled, this means that
1788 --foo arg1 --bar arg2 arg3
1792 --foo --bar arg1 arg2 arg3
1794 If an argument callback routine is specified, C<@ARGV> will always be
1795 empty upon succesful return of GetOptions() since all options have been
1796 processed. The only exception is when C<--> is used:
1798 --foo arg1 --bar arg2 -- arg3
1800 This will call the callback routine for arg1 and arg2, and then
1801 terminate GetOptions() leaving C<"arg2"> in C<@ARGV>.
1803 If C<require_order> is enabled, options processing
1804 terminates when the first non-option is encountered.
1806 --foo arg1 --bar arg2 arg3
1810 --foo -- arg1 --bar arg2 arg3
1812 If C<pass_through> is also enabled, options processing will terminate
1813 at the first unrecognized option, or non-option, whichever comes
1816 =item bundling (default: disabled)
1818 Enabling this option will allow single-character options to be
1819 bundled. To distinguish bundles from long option names, long options
1820 I<must> be introduced with C<--> and bundles with C<->.
1822 Note that, if you have options C<a>, C<l> and C<all>, and
1823 auto_abbrev enabled, possible arguments and option settings are:
1825 using argument sets option(s)
1826 ------------------------------------------
1829 -al, -la, -ala, -all,... a, l
1832 The suprising part is that C<--a> sets option C<a> (due to auto
1833 completion), not C<all>.
1835 Note: disabling C<bundling> also disables C<bundling_override>.
1837 =item bundling_override (default: disabled)
1839 If C<bundling_override> is enabled, bundling is enabled as with
1840 C<bundling> but now long option names override option bundles.
1842 Note: disabling C<bundling_override> also disables C<bundling>.
1844 B<Note:> Using option bundling can easily lead to unexpected results,
1845 especially when mixing long options and bundles. Caveat emptor.
1847 =item ignore_case (default: enabled)
1849 If enabled, case is ignored when matching long option names. If,
1850 however, bundling is enabled as well, single character options will be
1851 treated case-sensitive.
1853 With C<ignore_case>, option specifications for options that only
1854 differ in case, e.g., C<"foo"> and C<"Foo">, will be flagged as
1857 Note: disabling C<ignore_case> also disables C<ignore_case_always>.
1859 =item ignore_case_always (default: disabled)
1861 When bundling is in effect, case is ignored on single-character
1864 Note: disabling C<ignore_case_always> also disables C<ignore_case>.
1866 =item pass_through (default: disabled)
1868 Options that are unknown, ambiguous or supplied with an invalid option
1869 value are passed through in C<@ARGV> instead of being flagged as
1870 errors. This makes it possible to write wrapper scripts that process
1871 only part of the user supplied command line arguments, and pass the
1872 remaining options to some other program.
1874 If C<require_order> is enabled, options processing will terminate at
1875 the first unrecognized option, or non-option, whichever comes first.
1876 However, if C<permute> is enabled instead, results can become confusing.
1880 The string that starts options. If a constant string is not
1881 sufficient, see C<prefix_pattern>.
1883 =item prefix_pattern
1885 A Perl pattern that identifies the strings that introduce options.
1886 Default is C<(--|-|\+)> unless environment variable
1887 POSIXLY_CORRECT has been set, in which case it is C<(--|-)>.
1889 =item debug (default: disabled)
1891 Enable debugging output.
1895 =head1 Return values and Errors
1897 Configuration errors and errors in the option definitions are
1898 signalled using die() and will terminate the calling program unless
1899 the call to Getopt::Long::GetOptions() was embedded in C<eval { ...
1900 }>, or die() was trapped using C<$SIG{__DIE__}>.
1902 GetOptions returns true to indicate success.
1903 It returns false when the function detected one or more errors during
1904 option parsing. These errors are signalled using warn() and can be
1905 trapped with C<$SIG{__WARN__}>.
1907 Errors that can't happen are signalled using Carp::croak().
1911 The earliest development of C<newgetopt.pl> started in 1990, with Perl
1912 version 4. As a result, its development, and the development of
1913 Getopt::Long, has gone through several stages. Since backward
1914 compatibility has always been extremely important, the current version
1915 of Getopt::Long still supports a lot of constructs that nowadays are
1916 no longer necessary or otherwise unwanted. This section describes
1917 briefly some of these 'features'.
1919 =head2 Default destinations
1921 When no destination is specified for an option, GetOptions will store
1922 the resultant value in a global variable named C<opt_>I<XXX>, where
1923 I<XXX> is the primary name of this option. When a progam executes
1924 under C<use strict> (recommended), these variables must be
1925 pre-declared with our() or C<use vars>.
1927 our $opt_length = 0;
1928 GetOptions ('length=i'); # will store in $opt_length
1930 To yield a usable Perl variable, characters that are not part of the
1931 syntax for variables are translated to underscores. For example,
1932 C<--fpp-struct-return> will set the variable
1933 C<$opt_fpp_struct_return>. Note that this variable resides in the
1934 namespace of the calling program, not necessarily C<main>. For
1937 GetOptions ("size=i", "sizes=i@");
1939 with command line "-size 10 -sizes 24 -sizes 48" will perform the
1940 equivalent of the assignments
1943 @opt_sizes = (24, 48);
1945 =head2 Alternative option starters
1947 A string of alternative option starter characters may be passed as the
1948 first argument (or the first argument after a leading hash reference
1952 GetOptions ('/', 'length=i' => $len);
1954 Now the command line may look like:
1958 Note that to terminate options processing still requires a double dash
1961 GetOptions() will not interpret a leading C<< "<>" >> as option starters
1962 if the next argument is a reference. To force C<< "<" >> and C<< ">" >> as
1963 option starters, use C<< "><" >>. Confusing? Well, B<using a starter
1964 argument is strongly deprecated> anyway.
1966 =head2 Configuration variables
1968 Previous versions of Getopt::Long used variables for the purpose of
1969 configuring. Although manipulating these variables still work, it is
1970 strongly encouraged to use the C<Configure> routine that was introduced
1971 in version 2.17. Besides, it is much easier.
1973 =head1 Trouble Shooting
1975 =head2 Warning: Ignoring '!' modifier for short option
1977 This warning is issued when the '!' modifier is applied to a short
1978 (one-character) option and bundling is in effect. E.g.,
1980 Getopt::Long::Configure("bundling");
1981 GetOptions("foo|f!" => \$foo);
1983 Note that older Getopt::Long versions did not issue a warning, because
1984 the '!' modifier was applied to the first name only. This bug was
1987 Solution: separate the long and short names and apply the '!' to the
1988 long names only, e.g.,
1990 GetOptions("foo!" => \$foo, "f" => \$foo);
1992 =head2 GetOptions does not return a false result when an option is not supplied
1994 That's why they're called 'options'.
1996 =head2 GetOptions does not split the command line correctly
1998 The command line is not split by GetOptions, but by the command line
1999 interpreter (CLI). On Unix, this is the shell. On Windows, it is
2000 COMMAND.COM or CMD.EXE. Other operating systems have other CLIs.
2002 It is important to know that these CLIs may behave different when the
2003 command line contains special characters, in particular quotes or
2004 backslashes. For example, with Unix shells you can use single quotes
2005 (C<'>) and double quotes (C<">) to group words together. The following
2006 alternatives are equivalent on Unix:
2012 In case of doubt, insert the following statement in front of your Perl
2015 print STDERR (join("|",@ARGV),"\n");
2017 to verify how your CLI passes the arguments to the program.
2019 =head2 How do I put a "-?" option into a Getopt::Long?
2021 You can only obtain this using an alias, and Getopt::Long of at least
2025 GetOptions ("help|?"); # -help and -? will both set $opt_help
2029 Johan Vromans <jvromans@squirrel.nl>
2031 =head1 COPYRIGHT AND DISCLAIMER
2033 This program is Copyright 2002,1990 by Johan Vromans.
2034 This program is free software; you can redistribute it and/or
2035 modify it under the terms of the Perl Artistic License or the
2036 GNU General Public License as published by the Free Software
2037 Foundation; either version 2 of the License, or (at your option) any
2040 This program is distributed in the hope that it will be useful,
2041 but WITHOUT ANY WARRANTY; without even the implied warranty of
2042 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2043 GNU General Public License for more details.
2045 If you do not have a copy of the GNU General Public License write to
2046 the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,