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