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