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