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