This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Integrate perlio:
[perl5.git] / lib / Getopt / Long.pm
CommitLineData
a11f5414 1# GetOpt::Long.pm -- Universal options parsing
404cbe93 2
a11f5414
JV
3package Getopt::Long;
4
7d1b667f 5# RCS Status : $Id: GetoptLong.pl,v 2.28 2001-08-05 18:41:09+02 jv Exp $
404cbe93
PP
6# Author : Johan Vromans
7# Created On : Tue Sep 11 15:00:12 1990
8# Last Modified By: Johan Vromans
7d1b667f
JH
9# Last Modified On: Sun Aug 5 18:41:06 2001
10# Update Count : 751
404cbe93
PP
11# Status : Released
12
bb40d378 13################ Copyright ################
f06db76b 14
76744544 15# This program is Copyright 1990,2001 by Johan Vromans.
bb40d378 16# This program is free software; you can redistribute it and/or
1a505819
GS
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
20# later version.
21#
bb40d378
JV
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.
0b7031a2 26#
bb40d378 27# If you do not have a copy of the GNU General Public License write to
0b7031a2 28# the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
f9a400e4 29# MA 02139, USA.
f06db76b 30
bb40d378 31################ Module Preamble ################
404cbe93 32
76744544
JH
33use 5.004;
34
bb40d378 35use strict;
404cbe93 36
76744544 37use vars qw($VERSION $VERSION_STRING);
7d1b667f
JH
38$VERSION = 2.26;
39# For testing versions only.
40#$VERSION_STRING = "2.25_13";
e6d5c530 41
76744544
JH
42use Exporter;
43use AutoLoader qw(AUTOLOAD);
44
45use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
46@ISA = qw(Exporter);
47%EXPORT_TAGS = qw();
48BEGIN {
49 # Init immediately so their contents can be used in the 'use vars' below.
e6d5c530 50 @EXPORT = qw(&GetOptions $REQUIRE_ORDER $PERMUTE $RETURN_IN_ORDER);
e6d5c530 51 @EXPORT_OK = qw();
bb40d378 52}
404cbe93 53
bb40d378 54# User visible variables.
e6d5c530 55use vars @EXPORT, @EXPORT_OK;
bb40d378
JV
56use vars qw($error $debug $major_version $minor_version);
57# Deprecated visible variables.
58use vars qw($autoabbrev $getopt_compat $ignorecase $bundling $order
59 $passthrough);
e6d5c530 60# Official invisible variables.
10e5c9cc 61use vars qw($genprefix $caller $gnu_compat);
e6d5c530 62
0b7031a2 63# Public subroutines.
e6d5c530
JV
64sub Configure (@);
65sub config (@); # deprecated name
66sub GetOptions;
67
0b7031a2 68# Private subroutines.
e6d5c530
JV
69sub ConfigDefaults ();
70sub FindOption ($$$$$$$);
71sub Croak (@); # demand loading the real Croak
404cbe93 72
bb40d378 73################ Local Variables ################
404cbe93 74
e6d5c530
JV
75################ Resident subroutines ################
76
77sub ConfigDefaults () {
78 # Handle POSIX compliancy.
79 if ( defined $ENV{"POSIXLY_CORRECT"} ) {
80 $genprefix = "(--|-)";
81 $autoabbrev = 0; # no automatic abbrev of options
82 $bundling = 0; # no bundling of single letter switches
83 $getopt_compat = 0; # disallow '+' to start options
84 $order = $REQUIRE_ORDER;
85 }
86 else {
87 $genprefix = "(--|-|\\+)";
88 $autoabbrev = 1; # automatic abbrev of options
89 $bundling = 0; # bundling off by default
90 $getopt_compat = 1; # allow '+' to start options
91 $order = $PERMUTE;
92 }
93 # Other configurable settings.
94 $debug = 0; # for debugging
95 $error = 0; # error tally
96 $ignorecase = 1; # ignore case when matching options
97 $passthrough = 0; # leave unrecognized options alone
10e5c9cc
JH
98 $gnu_compat = 0; # require --opt=val if value is optional
99}
100
101# Override import.
102sub import {
103 my $pkg = shift; # package
104 my @syms = (); # symbols to import
105 my @config = (); # configuration
106 my $dest = \@syms; # symbols first
107 for ( @_ ) {
108 if ( $_ eq ':config' ) {
109 $dest = \@config; # config next
110 next;
111 }
112 push (@$dest, $_); # push
113 }
114 # Hide one level and call super.
115 local $Exporter::ExportLevel = 1;
116 $pkg->SUPER::import(@syms);
117 # And configure.
118 Configure (@config) if @config;
e6d5c530
JV
119}
120
121################ Initialization ################
122
123# Values for $order. See GNU getopt.c for details.
124($REQUIRE_ORDER, $PERMUTE, $RETURN_IN_ORDER) = (0..2);
125# Version major/minor numbers.
126($major_version, $minor_version) = $VERSION =~ /^(\d+)\.(\d+)/;
127
0b7031a2
GS
128ConfigDefaults();
129
10e5c9cc
JH
130################ OO Interface ################
131
132package Getopt::Long::Parser;
133
134# NOTE: The object oriented routines use $error for thread locking.
135my $_lock = sub {
136 lock ($Getopt::Long::error) if $] >= 5.005
137};
138
139# Store a copy of the default configuration. Since ConfigDefaults has
140# just been called, what we get from Configure is the default.
141my $default_config = do {
142 &$_lock;
143 Getopt::Long::Configure ()
144};
145
146sub new {
147 my $that = shift;
148 my $class = ref($that) || $that;
149 my %atts = @_;
150
151 # Register the callers package.
ea071ac9 152 my $self = { caller_pkg => (caller)[0] };
10e5c9cc
JH
153
154 bless ($self, $class);
155
156 # Process config attributes.
157 if ( defined $atts{config} ) {
158 &$_lock;
159 my $save = Getopt::Long::Configure ($default_config, @{$atts{config}});
160 $self->{settings} = Getopt::Long::Configure ($save);
161 delete ($atts{config});
162 }
163 # Else use default config.
164 else {
165 $self->{settings} = $default_config;
166 }
167
168 if ( %atts ) { # Oops
169 Getopt::Long::Croak(__PACKAGE__.": unhandled attributes: ".
170 join(" ", sort(keys(%atts))));
171 }
172
173 $self;
174}
175
176sub configure {
177 my ($self) = shift;
178
179 &$_lock;
180
181 # Restore settings, merge new settings in.
182 my $save = Getopt::Long::Configure ($self->{settings}, @_);
183
184 # Restore orig config and save the new config.
185 $self->{settings} = Configure ($save);
186}
187
188sub getoptions {
189 my ($self) = shift;
190
191 &$_lock;
192
193 # Restore config settings.
194 my $save = Getopt::Long::Configure ($self->{settings});
195
196 # Call main routine.
197 my $ret = 0;
ea071ac9 198 $Getopt::Long::caller = $self->{caller_pkg};
10e5c9cc
JH
199 eval { $ret = Getopt::Long::GetOptions (@_); };
200
201 # Restore saved settings.
202 Getopt::Long::Configure ($save);
203
204 # Handle errors and return value.
205 die ($@) if $@;
206 return $ret;
207}
208
209package Getopt::Long;
210
e6d5c530
JV
211################ Package return ################
212
2131;
214
215__END__
216
217################ AutoLoading subroutines ################
218
7d1b667f
JH
219package Getopt::Long;
220
221use strict;
222
223# RCS Status : $Id: GetoptLongAl.pl,v 2.34 2001-08-05 18:42:45+02 jv Exp $
e6d5c530
JV
224# Author : Johan Vromans
225# Created On : Fri Mar 27 11:50:30 1998
226# Last Modified By: Johan Vromans
7d1b667f
JH
227# Last Modified On: Sat Aug 4 17:32:13 2001
228# Update Count : 128
e6d5c530 229# Status : Released
404cbe93 230
bb40d378 231sub GetOptions {
404cbe93 232
bb40d378 233 my @optionlist = @_; # local copy of the option descriptions
e6d5c530
JV
234 my $argend = '--'; # option list terminator
235 my %opctl = (); # table of arg.specs (long and abbrevs)
236 my %bopctl = (); # table of arg.specs (bundles)
0b7031a2 237 my $pkg = $caller || (caller)[0]; # current context
bb40d378 238 # Needed if linkage is omitted.
e6d5c530 239 my %aliases= (); # alias table
bb40d378
JV
240 my @ret = (); # accum for non-options
241 my %linkage; # linkage
242 my $userlinkage; # user supplied HASH
e6d5c530
JV
243 my $opt; # current option
244 my $genprefix = $genprefix; # so we can call the same module many times
245 my @opctl; # the possible long option names
246
bb40d378 247 $error = '';
404cbe93 248
e6d5c530
JV
249 print STDERR ("GetOpt::Long $Getopt::Long::VERSION ",
250 "called from package \"$pkg\".",
251 "\n ",
7d1b667f 252 'GetOptionsAl $Revision: 2.34 $ ',
e6d5c530
JV
253 "\n ",
254 "ARGV: (@ARGV)",
255 "\n ",
256 "autoabbrev=$autoabbrev,".
257 "bundling=$bundling,",
258 "getopt_compat=$getopt_compat,",
10e5c9cc 259 "gnu_compat=$gnu_compat,",
e6d5c530
JV
260 "order=$order,",
261 "\n ",
262 "ignorecase=$ignorecase,",
263 "passthrough=$passthrough,",
264 "genprefix=\"$genprefix\".",
265 "\n")
bb40d378 266 if $debug;
404cbe93 267
0b7031a2 268 # Check for ref HASH as first argument.
bb40d378 269 # First argument may be an object. It's OK to use this as long
0b7031a2 270 # as it is really a hash underneath.
bb40d378 271 $userlinkage = undef;
7d1b667f 272 if ( @optionlist && ref($optionlist[0]) and
bb40d378
JV
273 "$optionlist[0]" =~ /^(?:.*\=)?HASH\([^\(]*\)$/ ) {
274 $userlinkage = shift (@optionlist);
275 print STDERR ("=> user linkage: $userlinkage\n") if $debug;
276 }
404cbe93 277
bb40d378
JV
278 # See if the first element of the optionlist contains option
279 # starter characters.
1a505819 280 # Be careful not to interpret '<>' as option starters.
7d1b667f 281 if ( @optionlist && $optionlist[0] =~ /^\W+$/
1a505819
GS
282 && !($optionlist[0] eq '<>'
283 && @optionlist > 0
284 && ref($optionlist[1])) ) {
bb40d378
JV
285 $genprefix = shift (@optionlist);
286 # Turn into regexp. Needs to be parenthesized!
287 $genprefix =~ s/(\W)/\\$1/g;
288 $genprefix = "([" . $genprefix . "])";
289 }
404cbe93 290
bb40d378
JV
291 # Verify correctness of optionlist.
292 %opctl = ();
293 %bopctl = ();
7d1b667f 294 while ( @optionlist ) {
bb40d378 295 my $opt = shift (@optionlist);
404cbe93 296
bb40d378 297 # Strip leading prefix so people can specify "--foo=i" if they like.
3a0431da 298 $opt = $+ if $opt =~ /^$genprefix+(.*)$/s;
404cbe93 299
bb40d378
JV
300 if ( $opt eq '<>' ) {
301 if ( (defined $userlinkage)
302 && !(@optionlist > 0 && ref($optionlist[0]))
303 && (exists $userlinkage->{$opt})
304 && ref($userlinkage->{$opt}) ) {
305 unshift (@optionlist, $userlinkage->{$opt});
306 }
0b7031a2 307 unless ( @optionlist > 0
bb40d378
JV
308 && ref($optionlist[0]) && ref($optionlist[0]) eq 'CODE' ) {
309 $error .= "Option spec <> requires a reference to a subroutine\n";
310 next;
311 }
312 $linkage{'<>'} = shift (@optionlist);
313 next;
314 }
404cbe93 315
10e5c9cc 316 # Match option spec. Allow '?' as an alias only.
7d1b667f 317 if ( $opt !~ /^((\w+[-\w]*)(\|(\?|\w[-\w]*)?)*)?([!~+]|[=:][ionfse][@%]?)?$/ ) {
bb40d378
JV
318 $error .= "Error in option spec: \"$opt\"\n";
319 next;
320 }
321 my ($o, $c, $a) = ($1, $5);
322 $c = '' unless defined $c;
404cbe93 323
10e5c9cc
JH
324 # $linko keeps track of the primary name the user specified.
325 # This name will be used for the internal or external linkage.
326 # In other words, if the user specifies "FoO|BaR", it will
327 # match any case combinations of 'foo' and 'bar', but if a global
328 # variable needs to be set, it will be $opt_FoO in the exact case
329 # as specified.
330 my $linko;
331
bb40d378
JV
332 if ( ! defined $o ) {
333 # empty -> '-' option
ea071ac9
JH
334 $linko = $o = '';
335 $opctl{''} = $c;
336 $bopctl{''} = $c if $bundling;
bb40d378
JV
337 }
338 else {
339 # Handle alias names
340 my @o = split (/\|/, $o);
10e5c9cc 341 $linko = $o = $o[0];
bb40d378
JV
342 # Force an alias if the option name is not locase.
343 $a = $o unless $o eq lc($o);
344 $o = lc ($o)
0b7031a2 345 if $ignorecase > 1
bb40d378
JV
346 || ($ignorecase
347 && ($bundling ? length($o) > 1 : 1));
404cbe93 348
bb40d378
JV
349 foreach ( @o ) {
350 if ( $bundling && length($_) == 1 ) {
351 $_ = lc ($_) if $ignorecase > 1;
352 if ( $c eq '!' ) {
353 $opctl{"no$_"} = $c;
7d1b667f 354 # warn ("Ignoring '!' modifier for short option $_\n");
265c41c2
GS
355 $opctl{$_} = $bopctl{$_} = '';
356 }
357 else {
358 $opctl{$_} = $bopctl{$_} = $c;
bb40d378 359 }
bb40d378
JV
360 }
361 else {
362 $_ = lc ($_) if $ignorecase;
363 if ( $c eq '!' ) {
364 $opctl{"no$_"} = $c;
265c41c2
GS
365 $opctl{$_} = ''
366 }
367 else {
368 $opctl{$_} = $c;
bb40d378 369 }
bb40d378
JV
370 }
371 if ( defined $a ) {
372 # Note alias.
373 $aliases{$_} = $a;
374 }
375 else {
376 # Set primary name.
377 $a = $_;
378 }
379 }
bb40d378 380 }
404cbe93 381
bb40d378
JV
382 # If no linkage is supplied in the @optionlist, copy it from
383 # the userlinkage if available.
384 if ( defined $userlinkage ) {
385 unless ( @optionlist > 0 && ref($optionlist[0]) ) {
10e5c9cc
JH
386 if ( exists $userlinkage->{$linko} &&
387 ref($userlinkage->{$linko}) ) {
388 print STDERR ("=> found userlinkage for \"$linko\": ",
389 "$userlinkage->{$linko}\n")
bb40d378 390 if $debug;
10e5c9cc 391 unshift (@optionlist, $userlinkage->{$linko});
bb40d378
JV
392 }
393 else {
394 # Do nothing. Being undefined will be handled later.
395 next;
396 }
397 }
398 }
404cbe93 399
bb40d378
JV
400 # Copy the linkage. If omitted, link to global variable.
401 if ( @optionlist > 0 && ref($optionlist[0]) ) {
10e5c9cc 402 print STDERR ("=> link \"$linko\" to $optionlist[0]\n")
bb40d378
JV
403 if $debug;
404 if ( ref($optionlist[0]) =~ /^(SCALAR|CODE)$/ ) {
10e5c9cc 405 $linkage{$linko} = shift (@optionlist);
bb40d378
JV
406 }
407 elsif ( ref($optionlist[0]) =~ /^(ARRAY)$/ ) {
10e5c9cc 408 $linkage{$linko} = shift (@optionlist);
bb40d378
JV
409 $opctl{$o} .= '@'
410 if $opctl{$o} ne '' and $opctl{$o} !~ /\@$/;
411 $bopctl{$o} .= '@'
0b7031a2 412 if $bundling and defined $bopctl{$o} and
bb40d378
JV
413 $bopctl{$o} ne '' and $bopctl{$o} !~ /\@$/;
414 }
415 elsif ( ref($optionlist[0]) =~ /^(HASH)$/ ) {
10e5c9cc 416 $linkage{$linko} = shift (@optionlist);
bb40d378
JV
417 $opctl{$o} .= '%'
418 if $opctl{$o} ne '' and $opctl{$o} !~ /\%$/;
419 $bopctl{$o} .= '%'
0b7031a2 420 if $bundling and defined $bopctl{$o} and
bb40d378
JV
421 $bopctl{$o} ne '' and $bopctl{$o} !~ /\%$/;
422 }
423 else {
424 $error .= "Invalid option linkage for \"$opt\"\n";
425 }
426 }
427 else {
428 # Link to global $opt_XXX variable.
429 # Make sure a valid perl identifier results.
10e5c9cc 430 my $ov = $linko;
bb40d378
JV
431 $ov =~ s/\W/_/g;
432 if ( $c =~ /@/ ) {
10e5c9cc 433 print STDERR ("=> link \"$linko\" to \@$pkg","::opt_$ov\n")
bb40d378 434 if $debug;
10e5c9cc 435 eval ("\$linkage{\$linko} = \\\@".$pkg."::opt_$ov;");
bb40d378
JV
436 }
437 elsif ( $c =~ /%/ ) {
10e5c9cc 438 print STDERR ("=> link \"$linko\" to \%$pkg","::opt_$ov\n")
bb40d378 439 if $debug;
10e5c9cc 440 eval ("\$linkage{\$linko} = \\\%".$pkg."::opt_$ov;");
bb40d378
JV
441 }
442 else {
10e5c9cc 443 print STDERR ("=> link \"$linko\" to \$$pkg","::opt_$ov\n")
bb40d378 444 if $debug;
10e5c9cc 445 eval ("\$linkage{\$linko} = \\\$".$pkg."::opt_$ov;");
bb40d378
JV
446 }
447 }
448 }
449
450 # Bail out if errors found.
451 die ($error) if $error;
452 $error = 0;
453
454 # Sort the possible long option names.
455 @opctl = sort(keys (%opctl)) if $autoabbrev;
456
457 # Show the options tables if debugging.
458 if ( $debug ) {
459 my ($arrow, $k, $v);
460 $arrow = "=> ";
461 while ( ($k,$v) = each(%opctl) ) {
462 print STDERR ($arrow, "\$opctl{\"$k\"} = \"$v\"\n");
463 $arrow = " ";
464 }
465 $arrow = "=> ";
466 while ( ($k,$v) = each(%bopctl) ) {
467 print STDERR ($arrow, "\$bopctl{\"$k\"} = \"$v\"\n");
468 $arrow = " ";
469 }
470 }
471
472 # Process argument list
0b7031a2
GS
473 my $goon = 1;
474 while ( $goon && @ARGV > 0 ) {
bb40d378
JV
475
476 #### Get next argument ####
477
478 $opt = shift (@ARGV);
bb40d378
JV
479 print STDERR ("=> option \"", $opt, "\"\n") if $debug;
480
481 #### Determine what we have ####
482
483 # Double dash is option list terminator.
484 if ( $opt eq $argend ) {
485 # Finish. Push back accumulated arguments and return.
0b7031a2 486 unshift (@ARGV, @ret)
bb40d378
JV
487 if $order == $PERMUTE;
488 return ($error == 0);
489 }
490
491 my $tryopt = $opt;
e6d5c530
JV
492 my $found; # success status
493 my $dsttype; # destination type ('@' or '%')
0b7031a2 494 my $incr; # destination increment
e6d5c530
JV
495 my $key; # key (if hash type)
496 my $arg; # option argument
497
0b7031a2
GS
498 ($found, $opt, $arg, $dsttype, $incr, $key) =
499 FindOption ($genprefix, $argend, $opt,
e6d5c530 500 \%opctl, \%bopctl, \@opctl, \%aliases);
bb40d378 501
e6d5c530 502 if ( $found ) {
0b7031a2 503
e6d5c530 504 # FindOption undefines $opt in case of errors.
bb40d378
JV
505 next unless defined $opt;
506
507 if ( defined $arg ) {
10e5c9cc
JH
508 if ( defined $aliases{$opt} ) {
509 print STDERR ("=> alias \"$opt\" -> \"$aliases{$opt}\"\n")
510 if $debug;
511 $opt = $aliases{$opt};
512 }
bb40d378
JV
513
514 if ( defined $linkage{$opt} ) {
515 print STDERR ("=> ref(\$L{$opt}) -> ",
516 ref($linkage{$opt}), "\n") if $debug;
517
518 if ( ref($linkage{$opt}) eq 'SCALAR' ) {
e6d5c530
JV
519 if ( $incr ) {
520 print STDERR ("=> \$\$L{$opt} += \"$arg\"\n")
521 if $debug;
522 if ( defined ${$linkage{$opt}} ) {
523 ${$linkage{$opt}} += $arg;
524 }
525 else {
526 ${$linkage{$opt}} = $arg;
527 }
528 }
529 else {
530 print STDERR ("=> \$\$L{$opt} = \"$arg\"\n")
531 if $debug;
532 ${$linkage{$opt}} = $arg;
533 }
bb40d378
JV
534 }
535 elsif ( ref($linkage{$opt}) eq 'ARRAY' ) {
536 print STDERR ("=> push(\@{\$L{$opt}, \"$arg\")\n")
537 if $debug;
538 push (@{$linkage{$opt}}, $arg);
539 }
540 elsif ( ref($linkage{$opt}) eq 'HASH' ) {
541 print STDERR ("=> \$\$L{$opt}->{$key} = \"$arg\"\n")
542 if $debug;
543 $linkage{$opt}->{$key} = $arg;
544 }
545 elsif ( ref($linkage{$opt}) eq 'CODE' ) {
546 print STDERR ("=> &L{$opt}(\"$opt\", \"$arg\")\n")
547 if $debug;
0b7031a2
GS
548 local ($@);
549 eval {
550 &{$linkage{$opt}}($opt, $arg);
551 };
552 print STDERR ("=> die($@)\n") if $debug && $@ ne '';
bee0ef1e
GS
553 if ( $@ =~ /^!/ ) {
554 if ( $@ =~ /^!FINISH\b/ ) {
555 $goon = 0;
556 }
0b7031a2
GS
557 }
558 elsif ( $@ ne '' ) {
559 warn ($@);
560 $error++;
561 }
bb40d378
JV
562 }
563 else {
564 print STDERR ("Invalid REF type \"", ref($linkage{$opt}),
565 "\" in linkage\n");
e6d5c530 566 Croak ("Getopt::Long -- internal error!\n");
bb40d378
JV
567 }
568 }
569 # No entry in linkage means entry in userlinkage.
e6d5c530 570 elsif ( $dsttype eq '@' ) {
bb40d378
JV
571 if ( defined $userlinkage->{$opt} ) {
572 print STDERR ("=> push(\@{\$L{$opt}}, \"$arg\")\n")
573 if $debug;
574 push (@{$userlinkage->{$opt}}, $arg);
575 }
576 else {
577 print STDERR ("=>\$L{$opt} = [\"$arg\"]\n")
578 if $debug;
579 $userlinkage->{$opt} = [$arg];
580 }
581 }
e6d5c530 582 elsif ( $dsttype eq '%' ) {
bb40d378
JV
583 if ( defined $userlinkage->{$opt} ) {
584 print STDERR ("=> \$L{$opt}->{$key} = \"$arg\"\n")
585 if $debug;
586 $userlinkage->{$opt}->{$key} = $arg;
587 }
588 else {
589 print STDERR ("=>\$L{$opt} = {$key => \"$arg\"}\n")
590 if $debug;
591 $userlinkage->{$opt} = {$key => $arg};
592 }
593 }
594 else {
e6d5c530
JV
595 if ( $incr ) {
596 print STDERR ("=> \$L{$opt} += \"$arg\"\n")
597 if $debug;
598 if ( defined $userlinkage->{$opt} ) {
599 $userlinkage->{$opt} += $arg;
600 }
601 else {
602 $userlinkage->{$opt} = $arg;
603 }
604 }
605 else {
606 print STDERR ("=>\$L{$opt} = \"$arg\"\n") if $debug;
607 $userlinkage->{$opt} = $arg;
608 }
bb40d378
JV
609 }
610 }
611 }
612
613 # Not an option. Save it if we $PERMUTE and don't have a <>.
614 elsif ( $order == $PERMUTE ) {
615 # Try non-options call-back.
616 my $cb;
617 if ( (defined ($cb = $linkage{'<>'})) ) {
0b7031a2
GS
618 local ($@);
619 eval {
620 &$cb ($tryopt);
621 };
622 print STDERR ("=> die($@)\n") if $debug && $@ ne '';
bee0ef1e
GS
623 if ( $@ =~ /^!/ ) {
624 if ( $@ =~ /^!FINISH\b/ ) {
625 $goon = 0;
626 }
0b7031a2
GS
627 }
628 elsif ( $@ ne '' ) {
629 warn ($@);
630 $error++;
631 }
bb40d378
JV
632 }
633 else {
634 print STDERR ("=> saving \"$tryopt\" ",
635 "(not an option, may permute)\n") if $debug;
636 push (@ret, $tryopt);
637 }
638 next;
639 }
640
641 # ...otherwise, terminate.
642 else {
643 # Push this one back and exit.
644 unshift (@ARGV, $tryopt);
645 return ($error == 0);
646 }
647
648 }
649
650 # Finish.
651 if ( $order == $PERMUTE ) {
652 # Push back accumulated arguments
653 print STDERR ("=> restoring \"", join('" "', @ret), "\"\n")
654 if $debug && @ret > 0;
655 unshift (@ARGV, @ret) if @ret > 0;
656 }
657
658 return ($error == 0);
659}
660
e6d5c530
JV
661# Option lookup.
662sub FindOption ($$$$$$$) {
bb40d378 663
e6d5c530
JV
664 # returns (1, $opt, $arg, $dsttype, $incr, $key) if okay,
665 # returns (0) otherwise.
bb40d378 666
e6d5c530
JV
667 my ($prefix, $argend, $opt, $opctl, $bopctl, $names, $aliases) = @_;
668 my $key; # hash key for a hash option
669 my $arg;
bb40d378 670
e6d5c530 671 print STDERR ("=> find \"$opt\", prefix=\"$prefix\"\n") if $debug;
bb40d378 672
ea071ac9
JH
673 return 0 unless $opt =~ /^$prefix(.*)$/s;
674 return 0 if $opt eq "-" && !defined $opctl->{""};
bb40d378 675
3a0431da 676 $opt = $+;
bb40d378
JV
677 my ($starter) = $1;
678
679 print STDERR ("=> split \"$starter\"+\"$opt\"\n") if $debug;
680
681 my $optarg = undef; # value supplied with --opt=value
682 my $rest = undef; # remainder from unbundling
683
684 # If it is a long option, it may include the value.
7d1b667f
JH
685 # With getopt_compat, not if bundling.
686 if ( ($starter eq "--"
687 || ($getopt_compat && ($bundling == 0 || $bundling == 2)))
688 && $opt =~ /^([^=]+)=(.*)$/s ) {
bb40d378
JV
689 $opt = $1;
690 $optarg = $2;
0b7031a2 691 print STDERR ("=> option \"", $opt,
bb40d378
JV
692 "\", optarg = \"$optarg\"\n") if $debug;
693 }
694
695 #### Look it up ###
696
697 my $tryopt = $opt; # option to try
e6d5c530 698 my $optbl = $opctl; # table to look it up (long names)
bb40d378 699 my $type;
e6d5c530
JV
700 my $dsttype = '';
701 my $incr = 0;
bb40d378
JV
702
703 if ( $bundling && $starter eq '-' ) {
704 # Unbundle single letter option.
ea071ac9 705 $rest = length ($tryopt) > 0 ? substr ($tryopt, 1) : "";
bb40d378
JV
706 $tryopt = substr ($tryopt, 0, 1);
707 $tryopt = lc ($tryopt) if $ignorecase > 1;
708 print STDERR ("=> $starter$tryopt unbundled from ",
709 "$starter$tryopt$rest\n") if $debug;
710 $rest = undef unless $rest ne '';
e6d5c530 711 $optbl = $bopctl; # look it up in the short names table
bb40d378
JV
712
713 # If bundling == 2, long options can override bundles.
714 if ( $bundling == 2 and
f9a400e4 715 defined ($rest) and
e6d5c530 716 defined ($type = $opctl->{$tryopt.$rest}) ) {
bb40d378
JV
717 print STDERR ("=> $starter$tryopt rebundled to ",
718 "$starter$tryopt$rest\n") if $debug;
719 $tryopt .= $rest;
720 undef $rest;
721 }
0b7031a2 722 }
bb40d378
JV
723
724 # Try auto-abbreviation.
725 elsif ( $autoabbrev ) {
726 # Downcase if allowed.
727 $tryopt = $opt = lc ($opt) if $ignorecase;
728 # Turn option name into pattern.
729 my $pat = quotemeta ($opt);
730 # Look up in option names.
e6d5c530 731 my @hits = grep (/^$pat/, @{$names});
bb40d378 732 print STDERR ("=> ", scalar(@hits), " hits (@hits) with \"$pat\" ",
e6d5c530 733 "out of ", scalar(@{$names}), "\n") if $debug;
bb40d378
JV
734
735 # Check for ambiguous results.
736 unless ( (@hits <= 1) || (grep ($_ eq $opt, @hits) == 1) ) {
737 # See if all matches are for the same option.
738 my %hit;
739 foreach ( @hits ) {
e6d5c530 740 $_ = $aliases->{$_} if defined $aliases->{$_};
bb40d378
JV
741 $hit{$_} = 1;
742 }
743 # Now see if it really is ambiguous.
744 unless ( keys(%hit) == 1 ) {
e6d5c530 745 return (0) if $passthrough;
bb40d378
JV
746 warn ("Option ", $opt, " is ambiguous (",
747 join(", ", @hits), ")\n");
748 $error++;
749 undef $opt;
e6d5c530 750 return (1, $opt,$arg,$dsttype,$incr,$key);
bb40d378
JV
751 }
752 @hits = keys(%hit);
753 }
754
755 # Complete the option name, if appropriate.
756 if ( @hits == 1 && $hits[0] ne $opt ) {
757 $tryopt = $hits[0];
758 $tryopt = lc ($tryopt) if $ignorecase;
759 print STDERR ("=> option \"$opt\" -> \"$tryopt\"\n")
760 if $debug;
761 }
762 }
763
764 # Map to all lowercase if ignoring case.
765 elsif ( $ignorecase ) {
766 $tryopt = lc ($opt);
767 }
768
769 # Check validity by fetching the info.
770 $type = $optbl->{$tryopt} unless defined $type;
771 unless ( defined $type ) {
e6d5c530 772 return (0) if $passthrough;
bb40d378
JV
773 warn ("Unknown option: ", $opt, "\n");
774 $error++;
e6d5c530 775 return (1, $opt,$arg,$dsttype,$incr,$key);
bb40d378
JV
776 }
777 # Apparently valid.
778 $opt = $tryopt;
10e5c9cc 779 print STDERR ("=> found \"$type\" for \"", $opt, "\"\n") if $debug;
bb40d378
JV
780
781 #### Determine argument status ####
782
783 # If it is an option w/o argument, we're almost finished with it.
e6d5c530 784 if ( $type eq '' || $type eq '!' || $type eq '+' ) {
bb40d378 785 if ( defined $optarg ) {
e6d5c530 786 return (0) if $passthrough;
bb40d378
JV
787 warn ("Option ", $opt, " does not take an argument\n");
788 $error++;
789 undef $opt;
790 }
e6d5c530 791 elsif ( $type eq '' || $type eq '+' ) {
bb40d378 792 $arg = 1; # supply explicit value
e6d5c530 793 $incr = $type eq '+';
bb40d378
JV
794 }
795 else {
796 substr ($opt, 0, 2) = ''; # strip NO prefix
797 $arg = 0; # supply explicit value
798 }
799 unshift (@ARGV, $starter.$rest) if defined $rest;
e6d5c530 800 return (1, $opt,$arg,$dsttype,$incr,$key);
bb40d378
JV
801 }
802
803 # Get mandatory status and type info.
804 my $mand;
e6d5c530 805 ($mand, $type, $dsttype, $key) = $type =~ /^(.)(.)([@%]?)$/;
bb40d378
JV
806
807 # Check if there is an option argument available.
10e5c9cc
JH
808 if ( $gnu_compat ) {
809 return (1, $opt, $optarg, $dsttype, $incr, $key)
810 if defined $optarg;
811 return (1, $opt, $type eq "s" ? '' : 0, $dsttype, $incr, $key)
812 if $mand eq ':';
813 }
814
815 # Check if there is an option argument available.
816 if ( defined $optarg
817 ? ($optarg eq '')
bb40d378
JV
818 : !(defined $rest || @ARGV > 0) ) {
819 # Complain if this option needs an argument.
820 if ( $mand eq "=" ) {
e6d5c530 821 return (0) if $passthrough;
bb40d378
JV
822 warn ("Option ", $opt, " requires an argument\n");
823 $error++;
824 undef $opt;
825 }
10e5c9cc 826 return (1, $opt, $type eq "s" ? '' : 0, $dsttype, $incr, $key);
bb40d378
JV
827 }
828
829 # Get (possibly optional) argument.
830 $arg = (defined $rest ? $rest
831 : (defined $optarg ? $optarg : shift (@ARGV)));
832
833 # Get key if this is a "name=value" pair for a hash option.
834 $key = undef;
e6d5c530 835 if ($dsttype eq '%' && defined $arg) {
0b7031a2 836 ($key, $arg) = ($arg =~ /^([^=]*)=(.*)$/s) ? ($1, $2) : ($arg, 1);
bb40d378
JV
837 }
838
839 #### Check if the argument is valid for this option ####
840
841 if ( $type eq "s" ) { # string
0b7031a2 842 # A mandatory string takes anything.
e6d5c530 843 return (1, $opt,$arg,$dsttype,$incr,$key) if $mand eq "=";
bb40d378 844
0b7031a2
GS
845 # An optional string takes almost anything.
846 return (1, $opt,$arg,$dsttype,$incr,$key)
e6d5c530
JV
847 if defined $optarg || defined $rest;
848 return (1, $opt,$arg,$dsttype,$incr,$key) if $arg eq "-"; # ??
bb40d378
JV
849
850 # Check for option or option list terminator.
851 if ($arg eq $argend ||
e6d5c530 852 $arg =~ /^$prefix.+/) {
bb40d378
JV
853 # Push back.
854 unshift (@ARGV, $arg);
855 # Supply empty value.
856 $arg = '';
857 }
858 }
859
7d1b667f
JH
860 elsif ( $type eq "n" || $type eq "i" # numeric/integer
861 || $type eq "o" ) { # dec/oct/hex/bin value
862
863 my $o_valid =
864 $type eq "o" ? "[-+]?[1-9][0-9]*|0x[0-9a-f]+|0b[01]+|0[0-7]*"
865 : "[-+]?[0-9]+";
866
867 if ( $bundling && defined $rest && $rest =~ /^($o_valid)(.*)$/si ) {
bb40d378
JV
868 $arg = $1;
869 $rest = $2;
7d1b667f 870 $arg = ($type eq "o" && $arg =~ /^0/) ? oct($arg) : 0+$arg;
bb40d378
JV
871 unshift (@ARGV, $starter.$rest) if defined $rest && $rest ne '';
872 }
7d1b667f
JH
873 elsif ( $arg =~ /^($o_valid)$/si ) {
874 $arg = ($type eq "o" && $arg =~ /^0/) ? oct($arg) : 0+$arg;
875 }
876 else {
bb40d378
JV
877 if ( defined $optarg || $mand eq "=" ) {
878 if ( $passthrough ) {
879 unshift (@ARGV, defined $rest ? $starter.$rest : $arg)
880 unless defined $optarg;
e6d5c530 881 return (0);
bb40d378
JV
882 }
883 warn ("Value \"", $arg, "\" invalid for option ",
7d1b667f
JH
884 $opt, " (",
885 $type eq "o" ? "extended " : "",
886 "number expected)\n");
bb40d378
JV
887 $error++;
888 undef $opt;
889 # Push back.
890 unshift (@ARGV, $starter.$rest) if defined $rest;
891 }
892 else {
893 # Push back.
894 unshift (@ARGV, defined $rest ? $starter.$rest : $arg);
895 # Supply default value.
896 $arg = 0;
897 }
898 }
899 }
900
901 elsif ( $type eq "f" ) { # real number, int is also ok
902 # We require at least one digit before a point or 'e',
903 # and at least one digit following the point and 'e'.
904 # [-]NN[.NN][eNN]
905 if ( $bundling && defined $rest &&
0b7031a2 906 $rest =~ /^([-+]?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?)(.*)$/s ) {
bb40d378 907 $arg = $1;
3a0431da 908 $rest = $+;
bb40d378
JV
909 unshift (@ARGV, $starter.$rest) if defined $rest && $rest ne '';
910 }
0b7031a2 911 elsif ( $arg !~ /^[-+]?[0-9.]+(\.[0-9]+)?([eE][-+]?[0-9]+)?$/ ) {
bb40d378
JV
912 if ( defined $optarg || $mand eq "=" ) {
913 if ( $passthrough ) {
914 unshift (@ARGV, defined $rest ? $starter.$rest : $arg)
915 unless defined $optarg;
e6d5c530 916 return (0);
bb40d378
JV
917 }
918 warn ("Value \"", $arg, "\" invalid for option ",
919 $opt, " (real number expected)\n");
920 $error++;
921 undef $opt;
922 # Push back.
923 unshift (@ARGV, $starter.$rest) if defined $rest;
924 }
925 else {
926 # Push back.
927 unshift (@ARGV, defined $rest ? $starter.$rest : $arg);
928 # Supply default value.
929 $arg = 0.0;
930 }
931 }
932 }
933 else {
e6d5c530 934 Croak ("GetOpt::Long internal error (Can't happen)\n");
bb40d378 935 }
e6d5c530
JV
936 return (1, $opt, $arg, $dsttype, $incr, $key);
937}
bb40d378 938
e6d5c530
JV
939# Getopt::Long Configuration.
940sub Configure (@) {
941 my (@options) = @_;
0b7031a2
GS
942
943 my $prevconfig =
944 [ $error, $debug, $major_version, $minor_version,
945 $autoabbrev, $getopt_compat, $ignorecase, $bundling, $order,
10e5c9cc 946 $gnu_compat, $passthrough, $genprefix ];
0b7031a2
GS
947
948 if ( ref($options[0]) eq 'ARRAY' ) {
949 ( $error, $debug, $major_version, $minor_version,
950 $autoabbrev, $getopt_compat, $ignorecase, $bundling, $order,
10e5c9cc 951 $gnu_compat, $passthrough, $genprefix ) = @{shift(@options)};
0b7031a2
GS
952 }
953
e6d5c530
JV
954 my $opt;
955 foreach $opt ( @options ) {
956 my $try = lc ($opt);
957 my $action = 1;
958 if ( $try =~ /^no_?(.*)$/s ) {
959 $action = 0;
960 $try = $+;
961 }
10e5c9cc
JH
962 if ( ($try eq 'default' or $try eq 'defaults') && $action ) {
963 ConfigDefaults ();
964 }
965 elsif ( ($try eq 'posix_default' or $try eq 'posix_defaults') ) {
966 local $ENV{POSIXLY_CORRECT};
967 $ENV{POSIXLY_CORRECT} = 1 if $action;
968 ConfigDefaults ();
e6d5c530
JV
969 }
970 elsif ( $try eq 'auto_abbrev' or $try eq 'autoabbrev' ) {
971 $autoabbrev = $action;
972 }
973 elsif ( $try eq 'getopt_compat' ) {
974 $getopt_compat = $action;
975 }
10e5c9cc
JH
976 elsif ( $try eq 'gnu_getopt' ) {
977 if ( $action ) {
978 $gnu_compat = 1;
979 $bundling = 1;
980 $getopt_compat = 0;
981 $permute = 1;
982 }
983 }
984 elsif ( $try eq 'gnu_compat' ) {
985 $gnu_compat = $action;
986 }
e6d5c530
JV
987 elsif ( $try eq 'ignorecase' or $try eq 'ignore_case' ) {
988 $ignorecase = $action;
989 }
990 elsif ( $try eq 'ignore_case_always' ) {
991 $ignorecase = $action ? 2 : 0;
992 }
993 elsif ( $try eq 'bundling' ) {
994 $bundling = $action;
995 }
996 elsif ( $try eq 'bundling_override' ) {
997 $bundling = $action ? 2 : 0;
998 }
999 elsif ( $try eq 'require_order' ) {
1000 $order = $action ? $REQUIRE_ORDER : $PERMUTE;
1001 }
1002 elsif ( $try eq 'permute' ) {
1003 $order = $action ? $PERMUTE : $REQUIRE_ORDER;
1004 }
1005 elsif ( $try eq 'pass_through' or $try eq 'passthrough' ) {
1006 $passthrough = $action;
1007 }
10e5c9cc 1008 elsif ( $try =~ /^prefix=(.+)$/ && $action ) {
e6d5c530
JV
1009 $genprefix = $1;
1010 # Turn into regexp. Needs to be parenthesized!
1011 $genprefix = "(" . quotemeta($genprefix) . ")";
1012 eval { '' =~ /$genprefix/; };
1013 Croak ("Getopt::Long: invalid pattern \"$genprefix\"") if $@;
1014 }
10e5c9cc 1015 elsif ( $try =~ /^prefix_pattern=(.+)$/ && $action ) {
e6d5c530
JV
1016 $genprefix = $1;
1017 # Parenthesize if needed.
0b7031a2 1018 $genprefix = "(" . $genprefix . ")"
e6d5c530
JV
1019 unless $genprefix =~ /^\(.*\)$/;
1020 eval { '' =~ /$genprefix/; };
1021 Croak ("Getopt::Long: invalid pattern \"$genprefix\"") if $@;
1022 }
1023 elsif ( $try eq 'debug' ) {
1024 $debug = $action;
1025 }
1026 else {
1027 Croak ("Getopt::Long: unknown config parameter \"$opt\"")
1028 }
bb40d378 1029 }
0b7031a2 1030 $prevconfig;
e6d5c530 1031}
bb40d378 1032
e6d5c530
JV
1033# Deprecated name.
1034sub config (@) {
1035 Configure (@_);
1036}
bb40d378 1037
e6d5c530
JV
1038# To prevent Carp from being loaded unnecessarily.
1039sub Croak (@) {
1040 require 'Carp.pm';
1041 $Carp::CarpLevel = 1;
1042 Carp::croak(@_);
1043};
bb40d378 1044
e6d5c530 1045################ Documentation ################
bb40d378
JV
1046
1047=head1 NAME
1048
0b7031a2 1049Getopt::Long - Extended processing of command line options
bb40d378
JV
1050
1051=head1 SYNOPSIS
1052
1053 use Getopt::Long;
7d1b667f
JH
1054 my $data = "file.dat";
1055 my $length = 24;
1056 my $verbose;
1057 $result = GetOptions ("length=i" => \$length, # numeric
1058 "file=s" => \$data, # string
1059 "verbose" => \$verbose); # flag
bb40d378
JV
1060
1061=head1 DESCRIPTION
1062
1063The Getopt::Long module implements an extended getopt function called
1064GetOptions(). This function adheres to the POSIX syntax for command
1065line options, with GNU extensions. In general, this means that options
1066have long names instead of single letters, and are introduced with a
1067double dash "--". Support for bundling of command line options, as was
1068the case with the more traditional single-letter approach, is provided
0b7031a2
GS
1069but not enabled by default.
1070
1071=head1 Command Line Options, an Introduction
1072
1073Command line operated programs traditionally take their arguments from
1074the command line, for example filenames or other information that the
1075program needs to know. Besides arguments, these programs often take
1076command line I<options> as well. Options are not necessary for the
1077program to work, hence the name 'option', but are used to modify its
1078default behaviour. For example, a program could do its job quietly,
1079but with a suitable option it could provide verbose information about
1080what it did.
1081
1082Command line options come in several flavours. Historically, they are
1083preceded by a single dash C<->, and consist of a single letter.
1084
1085 -l -a -c
1086
1087Usually, these single-character options can be bundled:
1088
1089 -lac
1090
1091Options can have values, the value is placed after the option
1092character. Sometimes with whitespace in between, sometimes not:
1093
1094 -s 24 -s24
1095
1096Due to the very cryptic nature of these options, another style was
1097developed that used long names. So instead of a cryptic C<-l> one
1098could use the more descriptive C<--long>. To distinguish between a
1099bundle of single-character options and a long one, two dashes are used
1100to precede the option name. Early implementations of long options used
1101a plus C<+> instead. Also, option values could be specified either
10e5c9cc 1102like
0b7031a2
GS
1103
1104 --size=24
1105
1106or
1107
1108 --size 24
1109
1110The C<+> form is now obsolete and strongly deprecated.
1111
1112=head1 Getting Started with Getopt::Long
1113
1114Getopt::Long is the Perl5 successor of C<newgetopt.pl>. This was
10e5c9cc 1115the first Perl module that provided support for handling the new style
0b7031a2
GS
1116of command line options, hence the name Getopt::Long. This module
1117also supports single-character options and bundling. In this case, the
1118options are restricted to alphabetic characters only, and the
1119characters C<?> and C<->.
1120
1121To use Getopt::Long from a Perl program, you must include the
1122following line in your Perl program:
1123
1124 use Getopt::Long;
1125
1126This will load the core of the Getopt::Long module and prepare your
1127program for using it. Most of the actual Getopt::Long code is not
1128loaded until you really call one of its functions.
1129
1130In the default configuration, options names may be abbreviated to
1131uniqueness, case does not matter, and a single dash is sufficient,
1132even for long option names. Also, options may be placed between
1133non-option arguments. See L<Configuring Getopt::Long> for more
1134details on how to configure Getopt::Long.
1135
1136=head2 Simple options
1137
1138The most simple options are the ones that take no values. Their mere
1139presence on the command line enables the option. Popular examples are:
1140
1141 --all --verbose --quiet --debug
1142
1143Handling simple options is straightforward:
1144
1145 my $verbose = ''; # option variable with default value (false)
1146 my $all = ''; # option variable with default value (false)
1147 GetOptions ('verbose' => \$verbose, 'all' => \$all);
1148
1149The call to GetOptions() parses the command line arguments that are
1150present in C<@ARGV> and sets the option variable to the value C<1> if
1151the option did occur on the command line. Otherwise, the option
1152variable is not touched. Setting the option value to true is often
1153called I<enabling> the option.
1154
1155The option name as specified to the GetOptions() function is called
1156the option I<specification>. Later we'll see that this specification
1157can contain more than just the option name. The reference to the
1158variable is called the option I<destination>.
1159
1160GetOptions() will return a true value if the command line could be
1161processed successfully. Otherwise, it will write error messages to
1162STDERR, and return a false result.
1163
1164=head2 A little bit less simple options
1165
1166Getopt::Long supports two useful variants of simple options:
1167I<negatable> options and I<incremental> options.
1168
1169A negatable option is specified with a exclamation mark C<!> after the
1170option name:
1171
1172 my $verbose = ''; # option variable with default value (false)
1173 GetOptions ('verbose!' => \$verbose);
1174
1175Now, using C<--verbose> on the command line will enable C<$verbose>,
1176as expected. But it is also allowed to use C<--noverbose>, which will
1177disable C<$verbose> by setting its value to C<0>. Using a suitable
1178default value, the program can find out whether C<$verbose> is false
1179by default, or disabled by using C<--noverbose>.
1180
1181An incremental option is specified with a plus C<+> after the
1182option name:
1183
1184 my $verbose = ''; # option variable with default value (false)
1185 GetOptions ('verbose+' => \$verbose);
1186
1187Using C<--verbose> on the command line will increment the value of
1188C<$verbose>. This way the program can keep track of how many times the
1189option occurred on the command line. For example, each occurrence of
1190C<--verbose> could increase the verbosity level of the program.
1191
1192=head2 Mixing command line option with other arguments
1193
1194Usually programs take command line options as well as other arguments,
1195for example, file names. It is good practice to always specify the
1196options first, and the other arguments last. Getopt::Long will,
1197however, allow the options and arguments to be mixed and 'filter out'
1198all the options before passing the rest of the arguments to the
1199program. To stop Getopt::Long from processing further arguments,
1200insert a double dash C<--> on the command line:
1201
1202 --size 24 -- --all
1203
1204In this example, C<--all> will I<not> be treated as an option, but
1205passed to the program unharmed, in C<@ARGV>.
1206
1207=head2 Options with values
1208
1209For options that take values it must be specified whether the option
1210value is required or not, and what kind of value the option expects.
1211
1212Three kinds of values are supported: integer numbers, floating point
1213numbers, and strings.
1214
1215If the option value is required, Getopt::Long will take the
1216command line argument that follows the option and assign this to the
1217option variable. If, however, the option value is specified as
1218optional, this will only be done if that value does not look like a
1219valid command line option itself.
bb40d378 1220
0b7031a2
GS
1221 my $tag = ''; # option variable with default value
1222 GetOptions ('tag=s' => \$tag);
bb40d378 1223
0b7031a2
GS
1224In the option specification, the option name is followed by an equals
1225sign C<=> and the letter C<s>. The equals sign indicates that this
1226option requires a value. The letter C<s> indicates that this value is
1227an arbitrary string. Other possible value types are C<i> for integer
1228values, and C<f> for floating point values. Using a colon C<:> instead
1229of the equals sign indicates that the option value is optional. In
1230this case, if no suitable value is supplied, string valued options get
1231an empty string C<''> assigned, while numeric options are set to C<0>.
bb40d378 1232
0b7031a2 1233=head2 Options with multiple values
bb40d378 1234
0b7031a2
GS
1235Options sometimes take several values. For example, a program could
1236use multiple directories to search for library files:
bb40d378 1237
0b7031a2 1238 --library lib/stdlib --library lib/extlib
bb40d378 1239
0b7031a2
GS
1240To accomplish this behaviour, simply specify an array reference as the
1241destination for the option:
bb40d378 1242
0b7031a2
GS
1243 my @libfiles = ();
1244 GetOptions ("library=s" => \@libfiles);
bb40d378 1245
0b7031a2
GS
1246Used with the example above, C<@libfiles> would contain two strings
1247upon completion: C<"lib/srdlib"> and C<"lib/extlib">, in that order.
1248It is also possible to specify that only integer or floating point
1249numbers are acceptible values.
bb40d378 1250
0b7031a2
GS
1251Often it is useful to allow comma-separated lists of values as well as
1252multiple occurrences of the options. This is easy using Perl's split()
1253and join() operators:
bb40d378 1254
0b7031a2
GS
1255 my @libfiles = ();
1256 GetOptions ("library=s" => \@libfiles);
1257 @libfiles = split(/,/,join(',',@libfiles));
bb40d378 1258
0b7031a2
GS
1259Of course, it is important to choose the right separator string for
1260each purpose.
3cb6de81 1261
0b7031a2 1262=head2 Options with hash values
bb40d378 1263
0b7031a2
GS
1264If the option destination is a reference to a hash, the option will
1265take, as value, strings of the form I<key>C<=>I<value>. The value will
1266be stored with the specified key in the hash.
bb40d378 1267
0b7031a2
GS
1268 my %defines = ();
1269 GetOptions ("define=s" => \%defines);
bb40d378 1270
0b7031a2
GS
1271When used with command line options:
1272
1273 --define os=linux --define vendor=redhat
1274
1275the hash C<%defines> will contain two keys, C<"os"> with value
1276C<"linux> and C<"vendor"> with value C<"redhat">.
1277It is also possible to specify that only integer or floating point
1278numbers are acceptible values. The keys are always taken to be strings.
1279
1280=head2 User-defined subroutines to handle options
1281
1282Ultimate control over what should be done when (actually: each time)
1283an option is encountered on the command line can be achieved by
1284designating a reference to a subroutine (or an anonymous subroutine)
1285as the option destination. When GetOptions() encounters the option, it
1286will call the subroutine with two arguments: the name of the option,
1287and the value to be assigned. It is up to the subroutine to store the
1288value, or do whatever it thinks is appropriate.
1289
1290A trivial application of this mechanism is to implement options that
1291are related to each other. For example:
1292
1293 my $verbose = ''; # option variable with default value (false)
1294 GetOptions ('verbose' => \$verbose,
1295 'quiet' => sub { $verbose = 0 });
1296
1297Here C<--verbose> and C<--quiet> control the same variable
1298C<$verbose>, but with opposite values.
1299
1300If the subroutine needs to signal an error, it should call die() with
1301the desired error message as its argument. GetOptions() will catch the
1302die(), issue the error message, and record that an error result must
1303be returned upon completion.
1304
bee0ef1e
GS
1305If the text of the error message starts with an exclamantion mark C<!>
1306it is interpreted specially by GetOptions(). There is currently one
1307special command implemented: C<die("!FINISH")> will cause GetOptions()
1308to stop processing options, as if it encountered a double dash C<-->.
0b7031a2
GS
1309
1310=head2 Options with multiple names
1311
1312Often it is user friendly to supply alternate mnemonic names for
1313options. For example C<--height> could be an alternate name for
1314C<--length>. Alternate names can be included in the option
1315specification, separated by vertical bar C<|> characters. To implement
1316the above example:
1317
1318 GetOptions ('length|height=f' => \$length);
1319
1320The first name is called the I<primary> name, the other names are
1321called I<aliases>.
1322
1323Multiple alternate names are possible.
1324
1325=head2 Case and abbreviations
1326
1327Without additional configuration, GetOptions() will ignore the case of
1328option names, and allow the options to be abbreviated to uniqueness.
1329
1330 GetOptions ('length|height=f' => \$length, "head" => \$head);
1331
1332This call will allow C<--l> and C<--L> for the length option, but
1333requires a least C<--hea> and C<--hei> for the head and height options.
1334
1335=head2 Summary of Option Specifications
1336
1337Each option specifier consists of two parts: the name specification
10e5c9cc 1338and the argument specification.
0b7031a2
GS
1339
1340The name specification contains the name of the option, optionally
1341followed by a list of alternative names separated by vertical bar
10e5c9cc 1342characters.
0b7031a2
GS
1343
1344 length option name is "length"
1345 length|size|l name is "length", aliases are "size" and "l"
1346
1347The argument specification is optional. If omitted, the option is
1348considered boolean, a value of 1 will be assigned when the option is
1349used on the command line.
1350
1351The argument specification can be
1352
bbc7dcd2 1353=over 4
bb40d378
JV
1354
1355=item !
1356
0b7031a2
GS
1357The option does not take an argument and may be negated, i.e. prefixed
1358by "no". E.g. C<"foo!"> will allow C<--foo> (a value of 1 will be
265c41c2
GS
1359assigned) and C<--nofoo> (a value of 0 will be assigned). If the
1360option has aliases, this applies to the aliases as well.
1361
1362Using negation on a single letter option when bundling is in effect is
1363pointless and will result in a warning.
bb40d378 1364
e6d5c530
JV
1365=item +
1366
0b7031a2
GS
1367The option does not take an argument and will be incremented by 1
1368every time it appears on the command line. E.g. C<"more+">, when used
1369with C<--more --more --more>, will increment the value three times,
1370resulting in a value of 3 (provided it was 0 or undefined at first).
e6d5c530 1371
0b7031a2 1372The C<+> specifier is ignored if the option destination is not a scalar.
e6d5c530 1373
0b7031a2 1374=item = I<type> [ I<desttype> ]
bb40d378 1375
0b7031a2
GS
1376The option requires an argument of the given type. Supported types
1377are:
bb40d378 1378
bbc7dcd2 1379=over 4
bb40d378 1380
0b7031a2 1381=item s
bb40d378 1382
0b7031a2
GS
1383String. An arbitrary sequence of characters. It is valid for the
1384argument to start with C<-> or C<-->.
bb40d378 1385
0b7031a2 1386=item i
bb40d378 1387
0b7031a2
GS
1388Integer. An optional leading plus or minus sign, followed by a
1389sequence of digits.
bb40d378 1390
7d1b667f
JH
1391=item o
1392
1393Extended integer, Perl style. This can be either an optional leading
1394plus or minus sign, followed by a sequence of digits, or an octal
1395string (a zero, optionally followed by '0', '1', .. '7'), or a
1396hexadecimal string (C<0x> followed by '0' .. '9', 'a' .. 'f', case
1397insensitive), or a binary string (C<0b> followed by a series of '0'
1398and '1').
1399
0b7031a2 1400=item f
bb40d378 1401
0b7031a2 1402Real number. For example C<3.14>, C<-6.23E24> and so on.
bb40d378 1403
0b7031a2
GS
1404=back
1405
1406The I<desttype> can be C<@> or C<%> to specify that the option is
1407list or a hash valued. This is only needed when the destination for
1408the option value is not otherwise specified. It should be omitted when
1409not needed.
1410
1411=item : I<type> [ I<desttype> ]
404cbe93 1412
0b7031a2
GS
1413Like C<=>, but designates the argument as optional.
1414If omitted, an empty string will be assigned to string values options,
1415and the value zero to numeric options.
404cbe93 1416
0b7031a2
GS
1417Note that if a string argument starts with C<-> or C<-->, it will be
1418considered an option on itself.
404cbe93
PP
1419
1420=back
1421
0b7031a2 1422=head1 Advanced Possibilities
404cbe93 1423
10e5c9cc
JH
1424=head2 Object oriented interface
1425
1426Getopt::Long can be used in an object oriented way as well:
1427
1428 use Getopt::Long;
1429 $p = new Getopt::Long::Parser;
1430 $p->configure(...configuration options...);
1431 if ($p->getoptions(...options descriptions...)) ...
1432
1433Configuration options can be passed to the constructor:
1434
1435 $p = new Getopt::Long::Parser
1436 config => [...configuration options...];
1437
1438For thread safety, each method call will acquire an exclusive lock to
1439the Getopt::Long module. So don't call these methods from a callback
1440routine!
1441
0b7031a2 1442=head2 Documentation and help texts
404cbe93 1443
0b7031a2
GS
1444Getopt::Long encourages the use of Pod::Usage to produce help
1445messages. For example:
404cbe93 1446
0b7031a2
GS
1447 use Getopt::Long;
1448 use Pod::Usage;
404cbe93 1449
0b7031a2
GS
1450 my $man = 0;
1451 my $help = 0;
404cbe93 1452
0b7031a2
GS
1453 GetOptions('help|?' => \$help, man => \$man) or pod2usage(2);
1454 pod2usage(1) if $help;
1455 pod2usage(-exitstatus => 0, -verbose => 2) if $man;
404cbe93 1456
0b7031a2 1457 __END__
404cbe93 1458
0b7031a2 1459 =head1 NAME
404cbe93 1460
0b7031a2 1461 sample - Using GetOpt::Long and Pod::Usage
404cbe93 1462
0b7031a2 1463 =head1 SYNOPSIS
404cbe93 1464
0b7031a2 1465 sample [options] [file ...]
404cbe93 1466
0b7031a2
GS
1467 Options:
1468 -help brief help message
1469 -man full documentation
381319f7 1470
0b7031a2 1471 =head1 OPTIONS
381319f7 1472
0b7031a2 1473 =over 8
381319f7 1474
0b7031a2 1475 =item B<-help>
381319f7 1476
0b7031a2 1477 Print a brief help message and exits.
404cbe93 1478
0b7031a2 1479 =item B<-man>
404cbe93 1480
0b7031a2 1481 Prints the manual page and exits.
404cbe93 1482
0b7031a2 1483 =back
404cbe93 1484
0b7031a2 1485 =head1 DESCRIPTION
404cbe93 1486
0b7031a2
GS
1487 B<This program> will read the given input file(s) and do someting
1488 useful with the contents thereof.
404cbe93 1489
0b7031a2 1490 =cut
535b5725 1491
0b7031a2 1492See L<Pod::Usage> for details.
535b5725 1493
0b7031a2 1494=head2 Storing options in a hash
404cbe93 1495
0b7031a2
GS
1496Sometimes, for example when there are a lot of options, having a
1497separate variable for each of them can be cumbersome. GetOptions()
1498supports, as an alternative mechanism, storing options in a hash.
404cbe93 1499
0b7031a2
GS
1500To obtain this, a reference to a hash must be passed I<as the first
1501argument> to GetOptions(). For each option that is specified on the
1502command line, the option value will be stored in the hash with the
1503option name as key. Options that are not actually used on the command
1504line will not be put in the hash, on other words,
1505C<exists($h{option})> (or defined()) can be used to test if an option
1506was used. The drawback is that warnings will be issued if the program
1507runs under C<use strict> and uses C<$h{option}> without testing with
1508exists() or defined() first.
381319f7 1509
0b7031a2
GS
1510 my %h = ();
1511 GetOptions (\%h, 'length=i'); # will store in $h{length}
f06db76b 1512
0b7031a2
GS
1513For options that take list or hash values, it is necessary to indicate
1514this by appending an C<@> or C<%> sign after the type:
f06db76b 1515
0b7031a2 1516 GetOptions (\%h, 'colours=s@'); # will push to @{$h{colours}}
f06db76b 1517
0b7031a2
GS
1518To make things more complicated, the hash may contain references to
1519the actual destinations, for example:
f06db76b 1520
0b7031a2
GS
1521 my $len = 0;
1522 my %h = ('length' => \$len);
1523 GetOptions (\%h, 'length=i'); # will store in $len
f06db76b 1524
0b7031a2 1525This example is fully equivalent with:
a11f5414 1526
0b7031a2
GS
1527 my $len = 0;
1528 GetOptions ('length=i' => \$len); # will store in $len
f06db76b 1529
0b7031a2
GS
1530Any mixture is possible. For example, the most frequently used options
1531could be stored in variables while all other options get stored in the
1532hash:
f06db76b 1533
0b7031a2
GS
1534 my $verbose = 0; # frequently referred
1535 my $debug = 0; # frequently referred
1536 my %h = ('verbose' => \$verbose, 'debug' => \$debug);
1537 GetOptions (\%h, 'verbose', 'debug', 'filter', 'size=i');
1538 if ( $verbose ) { ... }
1539 if ( exists $h{filter} ) { ... option 'filter' was specified ... }
f06db76b 1540
0b7031a2 1541=head2 Bundling
f06db76b 1542
0b7031a2
GS
1543With bundling it is possible to set several single-character options
1544at once. For example if C<a>, C<v> and C<x> are all valid options,
bb40d378 1545
0b7031a2 1546 -vax
bb40d378 1547
0b7031a2 1548would set all three.
f06db76b 1549
0b7031a2
GS
1550Getopt::Long supports two levels of bundling. To enable bundling, a
1551call to Getopt::Long::Configure is required.
bb40d378 1552
0b7031a2 1553The first level of bundling can be enabled with:
f06db76b 1554
0b7031a2 1555 Getopt::Long::Configure ("bundling");
404cbe93 1556
0b7031a2
GS
1557Configured this way, single-character options can be bundled but long
1558options B<must> always start with a double dash C<--> to avoid
1559abiguity. For example, when C<vax>, C<a>, C<v> and C<x> are all valid
1560options,
404cbe93 1561
0b7031a2 1562 -vax
381319f7 1563
10e5c9cc 1564would set C<a>, C<v> and C<x>, but
404cbe93 1565
0b7031a2 1566 --vax
404cbe93 1567
0b7031a2 1568would set C<vax>.
a11f5414 1569
0b7031a2
GS
1570The second level of bundling lifts this restriction. It can be enabled
1571with:
a11f5414 1572
0b7031a2 1573 Getopt::Long::Configure ("bundling_override");
a11f5414 1574
0b7031a2 1575Now, C<-vax> would set the option C<vax>.
a11f5414 1576
0b7031a2
GS
1577When any level of bundling is enabled, option values may be inserted
1578in the bundle. For example:
381319f7 1579
0b7031a2 1580 -h24w80
f06db76b 1581
0b7031a2 1582is equivalent to
f06db76b 1583
0b7031a2 1584 -h 24 -w 80
f06db76b 1585
0b7031a2
GS
1586When configured for bundling, single-character options are matched
1587case sensitive while long options are matched case insensitive. To
1588have the single-character options matched case insensitive as well,
1589use:
a0d0e21e 1590
0b7031a2 1591 Getopt::Long::Configure ("bundling", "ignorecase_always");
a0d0e21e 1592
0b7031a2 1593It goes without saying that bundling can be quite confusing.
404cbe93 1594
0b7031a2 1595=head2 The lonesome dash
404cbe93 1596
ea071ac9
JH
1597Normally, a lone dash C<-> on the command line will not be considered
1598an option. Option processing will terminate (unless "permute" is
1599configured) and the dash will be left in C<@ARGV>.
1600
1601It is possible to get special treatment for a lone dash. This can be
1602achieved by adding an option specification with an empty name, for
1603example:
a0d0e21e 1604
0b7031a2 1605 GetOptions ('' => \$stdio);
a11f5414 1606
ea071ac9
JH
1607A lone dash on the command line will now be a legal option, and using
1608it will set variable C<$stdio>.
a0d0e21e 1609
0b7031a2 1610=head2 Argument call-back
a0d0e21e 1611
0b7031a2
GS
1612A special option 'name' C<<>> can be used to designate a subroutine
1613to handle non-option arguments. When GetOptions() encounters an
1614argument that does not look like an option, it will immediately call this
1615subroutine and passes it the argument as a parameter.
a0d0e21e 1616
0b7031a2 1617For example:
a0d0e21e 1618
0b7031a2
GS
1619 my $width = 80;
1620 sub process { ... }
1621 GetOptions ('width=i' => \$width, '<>' => \&process);
a0d0e21e 1622
0b7031a2 1623When applied to the following command line:
a11f5414 1624
0b7031a2 1625 arg1 --width=72 arg2 --width=60 arg3
404cbe93 1626
10e5c9cc
JH
1627This will call
1628C<process("arg1")> while C<$width> is C<80>,
0b7031a2
GS
1629C<process("arg2")> while C<$width> is C<72>, and
1630C<process("arg3")> while C<$width> is C<60>.
381319f7 1631
0b7031a2
GS
1632This feature requires configuration option B<permute>, see section
1633L<Configuring Getopt::Long>.
a0d0e21e 1634
a0d0e21e 1635
0b7031a2
GS
1636=head1 Configuring Getopt::Long
1637
1638Getopt::Long can be configured by calling subroutine
1639Getopt::Long::Configure(). This subroutine takes a list of quoted
10e5c9cc
JH
1640strings, each specifying a configuration option to be enabled, e.g.
1641C<ignore_case>, or disabled, e.g. C<no_ignore_case>. Case does not
0b7031a2 1642matter. Multiple calls to Configure() are possible.
404cbe93 1643
10e5c9cc
JH
1644Alternatively, as of version 2.24, the configuration options may be
1645passed together with the C<use> statement:
1646
1647 use Getopt::Long qw(:config no_ignore_case bundling);
1648
bb40d378 1649The following options are available:
404cbe93 1650
bb40d378 1651=over 12
a0d0e21e 1652
bb40d378 1653=item default
a0d0e21e 1654
bb40d378
JV
1655This option causes all configuration options to be reset to their
1656default values.
404cbe93 1657
10e5c9cc
JH
1658=item posix_default
1659
1660This option causes all configuration options to be reset to their
1661default values as if the environment variable POSIXLY_CORRECT had
1662been set.
1663
bb40d378 1664=item auto_abbrev
404cbe93 1665
bb40d378 1666Allow option names to be abbreviated to uniqueness.
10e5c9cc
JH
1667Default is enabled unless environment variable
1668POSIXLY_CORRECT has been set, in which case C<auto_abbrev> is disabled.
404cbe93 1669
0b7031a2 1670=item getopt_compat
a0d0e21e 1671
0b7031a2 1672Allow C<+> to start options.
10e5c9cc
JH
1673Default is enabled unless environment variable
1674POSIXLY_CORRECT has been set, in which case C<getopt_compat> is disabled.
88e49c4e 1675
8ed53c8c
JH
1676=item gnu_compat
1677
1678C<gnu_compat> controls whether C<--opt=> is allowed, and what it should
1679do. Without C<gnu_compat>, C<--opt=> gives an error. With C<gnu_compat>,
1680C<--opt=> will give option C<opt> and empty value.
1681This is the way GNU getopt_long() does it.
1682
1683=item gnu_getopt
1684
1685This is a short way of setting C<gnu_compat> C<bundling> C<permute>
1686C<no_getopt_compat>. With C<gnu_getopt>, command line handling should be
1687fully compatible with GNU getopt_long().
1688
bb40d378 1689=item require_order
404cbe93 1690
0b7031a2 1691Whether command line arguments are allowed to be mixed with options.
10e5c9cc
JH
1692Default is disabled unless environment variable
1693POSIXLY_CORRECT has been set, in which case C<require_order> is enabled.
404cbe93 1694
0b7031a2 1695See also C<permute>, which is the opposite of C<require_order>.
a0d0e21e 1696
bb40d378 1697=item permute
404cbe93 1698
0b7031a2 1699Whether command line arguments are allowed to be mixed with options.
10e5c9cc
JH
1700Default is enabled unless environment variable
1701POSIXLY_CORRECT has been set, in which case C<permute> is disabled.
0b7031a2 1702Note that C<permute> is the opposite of C<require_order>.
a0d0e21e 1703
10e5c9cc 1704If C<permute> is enabled, this means that
a0d0e21e 1705
0b7031a2 1706 --foo arg1 --bar arg2 arg3
a0d0e21e 1707
bb40d378 1708is equivalent to
a0d0e21e 1709
0b7031a2 1710 --foo --bar arg1 arg2 arg3
a0d0e21e 1711
0b7031a2
GS
1712If an argument call-back routine is specified, C<@ARGV> will always be
1713empty upon succesful return of GetOptions() since all options have been
1714processed. The only exception is when C<--> is used:
a0d0e21e 1715
0b7031a2 1716 --foo arg1 --bar arg2 -- arg3
404cbe93 1717
bb40d378 1718will call the call-back routine for arg1 and arg2, and terminate
0b7031a2 1719GetOptions() leaving C<"arg2"> in C<@ARGV>.
381319f7 1720
10e5c9cc 1721If C<require_order> is enabled, options processing
bb40d378 1722terminates when the first non-option is encountered.
a0d0e21e 1723
0b7031a2 1724 --foo arg1 --bar arg2 arg3
381319f7 1725
bb40d378 1726is equivalent to
381319f7 1727
0b7031a2 1728 --foo -- arg1 --bar arg2 arg3
404cbe93 1729
ac634a9a
JH
1730If C<pass_through> is also enabled, options processing will terminate
1731at the first unrecognized option, or non-option, whichever comes
1732first.
1733
10e5c9cc 1734=item bundling (default: disabled)
404cbe93 1735
10e5c9cc 1736Enabling this option will allow single-character options to be bundled.
0b7031a2
GS
1737To distinguish bundles from long option names, long options I<must> be
1738introduced with C<--> and single-character options (and bundles) with
1739C<->.
bb40d378 1740
10e5c9cc 1741Note: disabling C<bundling> also disables C<bundling_override>.
a11f5414 1742
10e5c9cc 1743=item bundling_override (default: disabled)
381319f7 1744
10e5c9cc
JH
1745If C<bundling_override> is enabled, bundling is enabled as with
1746C<bundling> but now long option names override option bundles.
381319f7 1747
10e5c9cc 1748Note: disabling C<bundling_override> also disables C<bundling>.
381319f7 1749
bb40d378
JV
1750B<Note:> Using option bundling can easily lead to unexpected results,
1751especially when mixing long options and bundles. Caveat emptor.
381319f7 1752
10e5c9cc 1753=item ignore_case (default: enabled)
381319f7 1754
10e5c9cc 1755If enabled, case is ignored when matching long option names. Single
0b7031a2 1756character options will be treated case-sensitive.
381319f7 1757
10e5c9cc 1758Note: disabling C<ignore_case> also disables C<ignore_case_always>.
381319f7 1759
10e5c9cc 1760=item ignore_case_always (default: disabled)
a11f5414 1761
bb40d378 1762When bundling is in effect, case is ignored on single-character
10e5c9cc 1763options also.
381319f7 1764
10e5c9cc 1765Note: disabling C<ignore_case_always> also disables C<ignore_case>.
381319f7 1766
10e5c9cc 1767=item pass_through (default: disabled)
a0d0e21e 1768
0b7031a2
GS
1769Options that are unknown, ambiguous or supplied with an invalid option
1770value are passed through in C<@ARGV> instead of being flagged as
1771errors. This makes it possible to write wrapper scripts that process
1772only part of the user supplied command line arguments, and pass the
bb40d378 1773remaining options to some other program.
a0d0e21e 1774
ac634a9a
JH
1775If C<require_order> is enabled, options processing will terminate at
1776the first unrecognized option, or non-option, whichever comes first.
1777However, if C<permute> is enabled instead, results can become confusing.
16c18a90 1778
3a0431da
JV
1779=item prefix
1780
0b7031a2
GS
1781The string that starts options. If a constant string is not
1782sufficient, see C<prefix_pattern>.
3a0431da
JV
1783
1784=item prefix_pattern
1785
1786A Perl pattern that identifies the strings that introduce options.
1787Default is C<(--|-|\+)> unless environment variable
1788POSIXLY_CORRECT has been set, in which case it is C<(--|-)>.
1789
10e5c9cc 1790=item debug (default: disabled)
a0d0e21e 1791
10e5c9cc 1792Enable debugging output.
a0d0e21e 1793
bb40d378 1794=back
a0d0e21e 1795
0b7031a2 1796=head1 Return values and Errors
381319f7 1797
0b7031a2
GS
1798Configuration errors and errors in the option definitions are
1799signalled using die() and will terminate the calling program unless
1800the call to Getopt::Long::GetOptions() was embedded in C<eval { ...
1801}>, or die() was trapped using C<$SIG{__DIE__}>.
a0d0e21e 1802
10e5c9cc
JH
1803GetOptions returns true to indicate success.
1804It returns false when the function detected one or more errors during
1805option parsing. These errors are signalled using warn() and can be
1806trapped with C<$SIG{__WARN__}>.
a0d0e21e 1807
0b7031a2 1808Errors that can't happen are signalled using Carp::croak().
a0d0e21e 1809
0b7031a2 1810=head1 Legacy
a0d0e21e 1811
0b7031a2
GS
1812The earliest development of C<newgetopt.pl> started in 1990, with Perl
1813version 4. As a result, its development, and the development of
1814Getopt::Long, has gone through several stages. Since backward
1815compatibility has always been extremely important, the current version
1816of Getopt::Long still supports a lot of constructs that nowadays are
1817no longer necessary or otherwise unwanted. This section describes
1818briefly some of these 'features'.
a0d0e21e 1819
0b7031a2 1820=head2 Default destinations
a0d0e21e 1821
0b7031a2
GS
1822When no destination is specified for an option, GetOptions will store
1823the resultant value in a global variable named C<opt_>I<XXX>, where
1824I<XXX> is the primary name of this option. When a progam executes
1825under C<use strict> (recommended), these variables must be
1826pre-declared with our() or C<use vars>.
1827
1828 our $opt_length = 0;
1829 GetOptions ('length=i'); # will store in $opt_length
1830
1831To yield a usable Perl variable, characters that are not part of the
1832syntax for variables are translated to underscores. For example,
1833C<--fpp-struct-return> will set the variable
1834C<$opt_fpp_struct_return>. Note that this variable resides in the
1835namespace of the calling program, not necessarily C<main>. For
1836example:
1837
1838 GetOptions ("size=i", "sizes=i@");
1839
1840with command line "-size 10 -sizes 24 -sizes 48" will perform the
1841equivalent of the assignments
1842
1843 $opt_size = 10;
1844 @opt_sizes = (24, 48);
1845
1846=head2 Alternative option starters
1847
1848A string of alternative option starter characters may be passed as the
1849first argument (or the first argument after a leading hash reference
1850argument).
1851
1852 my $len = 0;
1853 GetOptions ('/', 'length=i' => $len);
1854
1855Now the command line may look like:
1856
1857 /length 24 -- arg
1858
1859Note that to terminate options processing still requires a double dash
1860C<-->.
1861
10e5c9cc
JH
1862GetOptions() will not interpret a leading C<< "<>" >> as option starters
1863if the next argument is a reference. To force C<< "<" >> and C<< ">" >> as
1864option starters, use C<< "><" >>. Confusing? Well, B<using a starter
0b7031a2
GS
1865argument is strongly deprecated> anyway.
1866
1867=head2 Configuration variables
1868
1869Previous versions of Getopt::Long used variables for the purpose of
10e5c9cc
JH
1870configuring. Although manipulating these variables still work, it is
1871strongly encouraged to use the C<Configure> routine that was introduced
1872in version 2.17. Besides, it is much easier.
1873
1874=head1 Trouble Shooting
1875
1876=head2 Warning: Ignoring '!' modifier for short option
1877
1878This warning is issued when the '!' modifier is applied to a short
1879(one-character) option and bundling is in effect. E.g.,
1880
1881 Getopt::Long::Configure("bundling");
1882 GetOptions("foo|f!" => \$foo);
1883
1884Note that older Getopt::Long versions did not issue a warning, because
1885the '!' modifier was applied to the first name only. This bug was
1886fixed in 2.22.
1887
1888Solution: separate the long and short names and apply the '!' to the
1889long names only, e.g.,
1890
1891 GetOptions("foo!" => \$foo, "f" => \$foo);
1892
1893=head2 GetOptions does not return a false result when an option is not supplied
1894
1895That's why they're called 'options'.
a0d0e21e 1896
bb40d378 1897=head1 AUTHOR
a11f5414 1898
10e5c9cc 1899Johan Vromans <jvromans@squirrel.nl>
a11f5414 1900
bb40d378 1901=head1 COPYRIGHT AND DISCLAIMER
a11f5414 1902
0b7031a2 1903This program is Copyright 2000,1990 by Johan Vromans.
bb40d378 1904This program is free software; you can redistribute it and/or
1a505819
GS
1905modify it under the terms of the Perl Artistic License or the
1906GNU General Public License as published by the Free Software
1907Foundation; either version 2 of the License, or (at your option) any
1908later version.
a11f5414 1909
bb40d378
JV
1910This program is distributed in the hope that it will be useful,
1911but WITHOUT ANY WARRANTY; without even the implied warranty of
1912MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1913GNU General Public License for more details.
a0d0e21e 1914
bb40d378 1915If you do not have a copy of the GNU General Public License write to
10e5c9cc 1916the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
f9a400e4 1917MA 02139, USA.
a0d0e21e 1918
bb40d378 1919=cut
0b7031a2 1920