Perlito5X/Getopt/Long.pm untested

filter: Statementstmt 0.0% 0 / 725 Branchbran 0.0% 0 / 608 Conditioncond 0.0% 0 / 307 MC/DCmcdc 0.0% 0 / 186 Subroutinesub 0.0% 0 / 60 Podpod 0.0% 0 / 34 totaltotal 0.0% 0 / 1920 CC 305 SCAR 88.6
CC
305
Cov
0%
GetOptionsFromArray
11342.0
FindOption
11342.0
Configure
1482.0
CRAP 7055.0
1 #! perl
2  
3 # Getopt::Long.pm -- Universal options parsing
4 # Author : Johan Vromans
5 # Created On : Tue Sep 11 15:00:12 1990
6 # Last Modified By: Johan Vromans
7 # Last Modified On: Thu Jun 9 14:50:37 2016
8 # Update Count : 1699
9 # Status : Released
10  
11 ################ Module Preamble ################
12  
13 package Getopt::Long;
14  
15 use 5.004;
16  
17 use strict;
18  
19 use vars qw($VERSION);
20 $VERSION = 2.49;
21 # For testing versions only.
22 use vars qw($VERSION_STRING);
23 $VERSION_STRING = "2.49";
24  
25 use Exporter;
26 use vars qw(@ISA @EXPORT @EXPORT_OK);
27 @ISA = qw(Exporter);
28  
29 # Exported subroutines.
30 sub GetOptions(@); # always
31 sub GetOptionsFromArray(@); # on demand
32 sub GetOptionsFromString(@); # on demand
33 sub Configure(@); # on demand
34 sub HelpMessage(@); # on demand
35 sub VersionMessage(@); # in demand
36  
37 BEGIN {
38 # Init immediately so their contents can be used in the 'use vars' below.
39 @EXPORT = qw(&GetOptions $REQUIRE_ORDER $PERMUTE $RETURN_IN_ORDER);
40 @EXPORT_OK = qw(&HelpMessage &VersionMessage &Configure
41 &GetOptionsFromArray &GetOptionsFromString);
42 }
43  
44 # User visible variables.
45 use vars @EXPORT, @EXPORT_OK;
46 use vars qw($error $debug $major_version $minor_version);
47 # Deprecated visible variables.
48 use vars qw($autoabbrev $getopt_compat $ignorecase $bundling $order
49 $passthrough);
50 # Official invisible variables.
51 use vars qw($genprefix $caller $gnu_compat $auto_help $auto_version $longprefix);
52  
53 # Really invisible variables.
54 my $bundling_values;
55  
56 # Public subroutines.
57 sub config(@); # deprecated name
58  
59 # Private subroutines.
60 sub ConfigDefaults();
61 sub ParseOptionSpec($$);
62 sub OptCtl($);
63 sub FindOption($$$$$);
64 sub ValidValue ($$$$$);
65  
66 ################ Local Variables ################
67  
68 # $requested_version holds the version that was mentioned in the 'use'
69 # or 'require', if any. It can be used to enable or disable specific
70 # features.
71 my $requested_version = 0;
72  
73 ################ Resident subroutines ################
74  
75 sub ConfigDefaults() {
76 # Handle POSIX compliancy.
77 if ( defined $ENV{"POSIXLY_CORRECT"} ) {
78 $genprefix = "(--|-)";
79 $autoabbrev = 0; # no automatic abbrev of options
80 $bundling = 0; # no bundling of single letter switches
81 $getopt_compat = 0; # disallow '+' to start options
82 $order = $REQUIRE_ORDER;
83 }
84 else {
85 $genprefix = "(--|-|\\+)";
86 $autoabbrev = 1; # automatic abbrev of options
87 $bundling = 0; # bundling off by default
88 $getopt_compat = 1; # allow '+' to start options
89 $order = $PERMUTE;
90 }
91 # Other configurable settings.
92 $debug = 0; # for debugging
93 $error = 0; # error tally
94 $ignorecase = 1; # ignore case when matching options
95 $passthrough = 0; # leave unrecognized options alone
96 $gnu_compat = 0; # require --opt=val if value is optional
97 $longprefix = "(--)"; # what does a long prefix look like
98 $bundling_values = 0; # no bundling of values
99 }
100  
101 # Override import.
102 sub import {
103 my $pkg = shift; # package
104 my @syms = (); # symbols to import
105 my @config = (); # configuration
106 my $dest = \@syms; # symbols first
107 for ( @_ ) {
108 if ( $_ eq ':config' ) {
109 $dest = \@config; # config next
110 next;
111 }
112 push(@$dest, $_); # push
113 }
114 # Hide one level and call super.
115 local $Exporter::ExportLevel = 1;
116 push(@syms, qw(&GetOptions)) if @syms; # always export GetOptions
117 $requested_version = 0;
118 $pkg->SUPER::import(@syms);
119 # And configure.
120 Configure(@config) if @config;
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  
130 ConfigDefaults();
131  
132 ################ OO Interface ################
133  
134 package Getopt::Long::Parser;
135  
136 # Store a copy of the default configuration. Since ConfigDefaults has
137 # just been called, what we get from Configure is the default.
138 my $default_config = do {
139 Getopt::Long::Configure ()
140 };
141  
142 sub new {
143 my $that = shift;
144 my $class = ref($that) || $that;
145 my %atts = @_;
146  
147 # Register the callers package.
148 my $self = { caller_pkg => (caller)[0] };
149  
150 bless ($self, $class);
151  
152 # Process config attributes.
153 if ( defined $atts{config} ) {
154 my $save = Getopt::Long::Configure ($default_config, @{$atts{config}});
155 $self->{settings} = Getopt::Long::Configure ($save);
156 delete ($atts{config});
157 }
158 # Else use default config.
159 else {
160 $self->{settings} = $default_config;
161 }
162  
163 if ( %atts ) { # Oops
164 die(__PACKAGE__.": unhandled attributes: ".
165 join(" ", sort(keys(%atts)))."\n");
166 }
167  
168 $self;
169 }
170  
171 sub configure {
172 my ($self) = shift;
173  
174 # Restore settings, merge new settings in.
175 my $save = Getopt::Long::Configure ($self->{settings}, @_);
176  
177 # Restore orig config and save the new config.
178 $self->{settings} = Getopt::Long::Configure ($save);
179 }
180  
181 sub getoptions {
182 my ($self) = shift;
183  
184 return $self->getoptionsfromarray(\@ARGV, @_);
185 }
186  
187 sub getoptionsfromarray {
188 my ($self) = shift;
189  
190 # Restore config settings.
191 my $save = Getopt::Long::Configure ($self->{settings});
192  
193 # Call main routine.
194 my $ret = 0;
195 $Getopt::Long::caller = $self->{caller_pkg};
196  
197 eval {
198 # Locally set exception handler to default, otherwise it will
199 # be called implicitly here, and again explicitly when we try
200 # to deliver the messages.
201 local ($SIG{__DIE__}) = 'DEFAULT';
202 $ret = Getopt::Long::GetOptionsFromArray (@_);
203 };
204  
205 # Restore saved settings.
206 Getopt::Long::Configure ($save);
207  
208 # Handle errors and return value.
209 die ($@) if $@;
210 return $ret;
211 }
212  
213 package Getopt::Long;
214  
215 ################ Back to Normal ################
216  
217 # Indices in option control info.
218 # Note that ParseOptions uses the fields directly. Search for 'hard-wired'.
219 use constant CTL_TYPE => 0;
220 #use constant CTL_TYPE_FLAG => '';
221 #use constant CTL_TYPE_NEG => '!';
222 #use constant CTL_TYPE_INCR => '+';
223 #use constant CTL_TYPE_INT => 'i';
224 #use constant CTL_TYPE_INTINC => 'I';
225 #use constant CTL_TYPE_XINT => 'o';
226 #use constant CTL_TYPE_FLOAT => 'f';
227 #use constant CTL_TYPE_STRING => 's';
228  
229 use constant CTL_CNAME => 1;
230  
231 use constant CTL_DEFAULT => 2;
232  
233 use constant CTL_DEST => 3;
234 use constant CTL_DEST_SCALAR => 0;
235 use constant CTL_DEST_ARRAY => 1;
236 use constant CTL_DEST_HASH => 2;
237 use constant CTL_DEST_CODE => 3;
238  
239 use constant CTL_AMIN => 4;
240 use constant CTL_AMAX => 5;
241  
242 # FFU.
243 #use constant CTL_RANGE => ;
244 #use constant CTL_REPEAT => ;
245  
246 # Rather liberal patterns to match numbers.
247 use constant PAT_INT => "[-+]?_*[0-9][0-9_]*";
248 use constant PAT_XINT =>
249 "(?:".
250 "[-+]?_*[1-9][0-9_]*".
251 "|".
252 "0x_*[0-9a-f][0-9a-f_]*".
253 "|".
254 "0b_*[01][01_]*".
255 "|".
256 "0[0-7_]*".
257 ")";
258 use constant PAT_FLOAT =>
259 "[-+]?". # optional sign
260 "(?=[0-9.])". # must start with digit or dec.point
261 "[0-9_]*". # digits before the dec.point
262 "(\.[0-9_]+)?". # optional fraction
263 "([eE][-+]?[0-9_]+)?"; # optional exponent
264  
265 sub GetOptions(@) {
266 # Shift in default array.
267 unshift(@_, \@ARGV);
268 # Try to keep caller() and Carp consistent.
269 goto &GetOptionsFromArray;
270 }
271  
272 sub GetOptionsFromString(@) {
273 my ($string) = shift;
274 require Text::ParseWords;
275 my $args = [ Text::ParseWords::shellwords($string) ];
276 $caller ||= (caller)[0]; # current context
277 my $ret = GetOptionsFromArray($args, @_);
278 return ( $ret, $args ) if wantarray;
279 if ( @$args ) {
280 $ret = 0;
281 warn("GetOptionsFromString: Excess data \"@$args\" in string \"$string\"\n");
282 }
283 $ret;
284 }
285  
286 sub GetOptionsFromArray(@) {
287  
288 my ($argv, @optionlist) = @_; # local copy of the option descriptions
289 my $argend = '--'; # option list terminator
290 my %opctl = (); # table of option specs
291 my $pkg = $caller || (caller)[0]; # current context
292 # Needed if linkage is omitted.
293 my @ret = (); # accum for non-options
294 my %linkage; # linkage
295 my $userlinkage; # user supplied HASH
296 my $opt; # current option
297 my $prefix = $genprefix; # current prefix
298  
299 $error = '';
300  
301 if ( $debug ) {
302 # Avoid some warnings if debugging.
303 local ($^W) = 0;
304 print STDERR
305 ("Getopt::Long $Getopt::Long::VERSION ",
306 "called from package \"$pkg\".",
307 "\n ",
308 "argv: ",
309 defined($argv)
310 ? UNIVERSAL::isa( $argv, 'ARRAY' ) ? "(@$argv)" : $argv
311 : "<undef>",
312 "\n ",
313 "autoabbrev=$autoabbrev,".
314 "bundling=$bundling,",
315 "bundling_values=$bundling_values,",
316 "getopt_compat=$getopt_compat,",
317 "gnu_compat=$gnu_compat,",
318 "order=$order,",
319 "\n ",
320 "ignorecase=$ignorecase,",
321 "requested_version=$requested_version,",
322 "passthrough=$passthrough,",
323 "genprefix=\"$genprefix\",",
324 "longprefix=\"$longprefix\".",
325 "\n");
326 }
327  
328 # Check for ref HASH as first argument.
329 # First argument may be an object. It's OK to use this as long
330 # as it is really a hash underneath.
331 $userlinkage = undef;
332 if ( @optionlist && ref($optionlist[0]) and
333 UNIVERSAL::isa($optionlist[0],'HASH') ) {
334 $userlinkage = shift (@optionlist);
335 print STDERR ("=> user linkage: $userlinkage\n") if $debug;
336 }
337  
338 # See if the first element of the optionlist contains option
339 # starter characters.
340 # Be careful not to interpret '<>' as option starters.
341 if ( @optionlist && $optionlist[0] =~ /^\W+$/
342 && !($optionlist[0] eq '<>'
343 && @optionlist > 0
344 && ref($optionlist[1])) ) {
345 $prefix = shift (@optionlist);
346 # Turn into regexp. Needs to be parenthesized!
347 $prefix =~ s/(\W)/\\$1/g;
348 $prefix = "([" . $prefix . "])";
349 print STDERR ("=> prefix=\"$prefix\"\n") if $debug;
350 }
351  
352 # Verify correctness of optionlist.
353 %opctl = ();
354 while ( @optionlist ) {
355 my $opt = shift (@optionlist);
356  
357 unless ( defined($opt) ) {
358 $error .= "Undefined argument in option spec\n";
359 next;
360 }
361  
362 # Strip leading prefix so people can specify "--foo=i" if they like.
363 $opt = $+ if $opt =~ /^$prefix+(.*)$/s;
364  
365 if ( $opt eq '<>' ) {
366 if ( (defined $userlinkage)
367 && !(@optionlist > 0 && ref($optionlist[0]))
368 && (exists $userlinkage->{$opt})
369 && ref($userlinkage->{$opt}) ) {
370 unshift (@optionlist, $userlinkage->{$opt});
371 }
372 unless ( @optionlist > 0
373 && ref($optionlist[0]) && ref($optionlist[0]) eq 'CODE' ) {
374 $error .= "Option spec <> requires a reference to a subroutine\n";
375 # Kill the linkage (to avoid another error).
376 shift (@optionlist)
377 if @optionlist && ref($optionlist[0]);
378 next;
379 }
380 $linkage{'<>'} = shift (@optionlist);
381 next;
382 }
383  
384 # Parse option spec.
385 my ($name, $orig) = ParseOptionSpec ($opt, \%opctl);
386 unless ( defined $name ) {
387 # Failed. $orig contains the error message. Sorry for the abuse.
388 $error .= $orig;
389 # Kill the linkage (to avoid another error).
390 shift (@optionlist)
391 if @optionlist && ref($optionlist[0]);
392 next;
393 }
394  
395 # If no linkage is supplied in the @optionlist, copy it from
396 # the userlinkage if available.
397 if ( defined $userlinkage ) {
398 unless ( @optionlist > 0 && ref($optionlist[0]) ) {
399 if ( exists $userlinkage->{$orig} &&
400 ref($userlinkage->{$orig}) ) {
401 print STDERR ("=> found userlinkage for \"$orig\": ",
402 "$userlinkage->{$orig}\n")
403 if $debug;
404 unshift (@optionlist, $userlinkage->{$orig});
405 }
406 else {
407 # Do nothing. Being undefined will be handled later.
408 next;
409 }
410 }
411 }
412  
413 # Copy the linkage. If omitted, link to global variable.
414 if ( @optionlist > 0 && ref($optionlist[0]) ) {
415 print STDERR ("=> link \"$orig\" to $optionlist[0]\n")
416 if $debug;
417 my $rl = ref($linkage{$orig} = shift (@optionlist));
418  
419 if ( $rl eq "ARRAY" ) {
420 $opctl{$name}[CTL_DEST] = CTL_DEST_ARRAY;
421 }
422 elsif ( $rl eq "HASH" ) {
423 $opctl{$name}[CTL_DEST] = CTL_DEST_HASH;
424 }
425 elsif ( $rl eq "SCALAR" || $rl eq "REF" ) {
426 # if ( $opctl{$name}[CTL_DEST] == CTL_DEST_ARRAY ) {
427 # my $t = $linkage{$orig};
428 # $$t = $linkage{$orig} = [];
429 # }
430 # elsif ( $opctl{$name}[CTL_DEST] == CTL_DEST_HASH ) {
431 # }
432 # else {
433 # Ok.
434 # }
435 }
436 elsif ( $rl eq "CODE" ) {
437 # Ok.
438 }
439 else {
440 $error .= "Invalid option linkage for \"$opt\"\n";
441 }
442 }
443 else {
444 # Link to global $opt_XXX variable.
445 # Make sure a valid perl identifier results.
446 my $ov = $orig;
447 $ov =~ s/\W/_/g;
448 if ( $opctl{$name}[CTL_DEST] == CTL_DEST_ARRAY ) {
449 print STDERR ("=> link \"$orig\" to \@$pkg","::opt_$ov\n")
450 if $debug;
451 eval ("\$linkage{\$orig} = \\\@".$pkg."::opt_$ov;");
452 }
453 elsif ( $opctl{$name}[CTL_DEST] == CTL_DEST_HASH ) {
454 print STDERR ("=> link \"$orig\" to \%$pkg","::opt_$ov\n")
455 if $debug;
456 eval ("\$linkage{\$orig} = \\\%".$pkg."::opt_$ov;");
457 }
458 else {
459 print STDERR ("=> link \"$orig\" to \$$pkg","::opt_$ov\n")
460 if $debug;
461 eval ("\$linkage{\$orig} = \\\$".$pkg."::opt_$ov;");
462 }
463 }
464  
465 if ( $opctl{$name}[CTL_TYPE] eq 'I'
466 && ( $opctl{$name}[CTL_DEST] == CTL_DEST_ARRAY
467 || $opctl{$name}[CTL_DEST] == CTL_DEST_HASH )
468 ) {
469 $error .= "Invalid option linkage for \"$opt\"\n";
470 }
471  
472 }
473  
474 $error .= "GetOptionsFromArray: 1st parameter is not an array reference\n"
475 unless $argv && UNIVERSAL::isa( $argv, 'ARRAY' );
476  
477 # Bail out if errors found.
478 die ($error) if $error;
479 $error = 0;
480  
481 # Supply --version and --help support, if needed and allowed.
482 if ( defined($auto_version) ? $auto_version : ($requested_version >= 2.3203) ) {
483 if ( !defined($opctl{version}) ) {
484 $opctl{version} = ['','version',0,CTL_DEST_CODE,undef];
485 $linkage{version} = \&VersionMessage;
486 }
487 $auto_version = 1;
488 }
489 if ( defined($auto_help) ? $auto_help : ($requested_version >= 2.3203) ) {
490 if ( !defined($opctl{help}) && !defined($opctl{'?'}) ) {
491 $opctl{help} = $opctl{'?'} = ['','help',0,CTL_DEST_CODE,undef];
492 $linkage{help} = \&HelpMessage;
493 }
494 $auto_help = 1;
495 }
496  
497 # Show the options tables if debugging.
498 if ( $debug ) {
499 my ($arrow, $k, $v);
500 $arrow = "=> ";
501 while ( ($k,$v) = each(%opctl) ) {
502 print STDERR ($arrow, "\$opctl{$k} = $v ", OptCtl($v), "\n");
503 $arrow = " ";
504 }
505 }
506  
507 # Process argument list
508 my $goon = 1;
509 while ( $goon && @$argv > 0 ) {
510  
511 # Get next argument.
512 $opt = shift (@$argv);
513 print STDERR ("=> arg \"", $opt, "\"\n") if $debug;
514  
515 # Double dash is option list terminator.
516 if ( defined($opt) && $opt eq $argend ) {
517 push (@ret, $argend) if $passthrough;
518 last;
519 }
520  
521 # Look it up.
522 my $tryopt = $opt;
523 my $found; # success status
524 my $key; # key (if hash type)
525 my $arg; # option argument
526 my $ctl; # the opctl entry
527  
528 ($found, $opt, $ctl, $arg, $key) =
529 FindOption ($argv, $prefix, $argend, $opt, \%opctl);
530  
531 if ( $found ) {
532  
533 # FindOption undefines $opt in case of errors.
534 next unless defined $opt;
535  
536 my $argcnt = 0;
537 while ( defined $arg ) {
538  
539 # Get the canonical name.
540 print STDERR ("=> cname for \"$opt\" is ") if $debug;
541 $opt = $ctl->[CTL_CNAME];
542 print STDERR ("\"$ctl->[CTL_CNAME]\"\n") if $debug;
543  
544 if ( defined $linkage{$opt} ) {
545 print STDERR ("=> ref(\$L{$opt}) -> ",
546 ref($linkage{$opt}), "\n") if $debug;
547  
548 if ( ref($linkage{$opt}) eq 'SCALAR'
549 || ref($linkage{$opt}) eq 'REF' ) {
550 if ( $ctl->[CTL_TYPE] eq '+' ) {
551 print STDERR ("=> \$\$L{$opt} += \"$arg\"\n")
552 if $debug;
553 if ( defined ${$linkage{$opt}} ) {
554 ${$linkage{$opt}} += $arg;
555 }
556 else {
557 ${$linkage{$opt}} = $arg;
558 }
559 }
560 elsif ( $ctl->[CTL_DEST] == CTL_DEST_ARRAY ) {
561 print STDERR ("=> ref(\$L{$opt}) auto-vivified",
562 " to ARRAY\n")
563 if $debug;
564 my $t = $linkage{$opt};
565 $$t = $linkage{$opt} = [];
566 print STDERR ("=> push(\@{\$L{$opt}, \"$arg\")\n")
567 if $debug;
568 push (@{$linkage{$opt}}, $arg);
569 }
570 elsif ( $ctl->[CTL_DEST] == CTL_DEST_HASH ) {
571 print STDERR ("=> ref(\$L{$opt}) auto-vivified",
572 " to HASH\n")
573 if $debug;
574 my $t = $linkage{$opt};
575 $$t = $linkage{$opt} = {};
576 print STDERR ("=> \$\$L{$opt}->{$key} = \"$arg\"\n")
577 if $debug;
578 $linkage{$opt}->{$key} = $arg;
579 }
580 else {
581 print STDERR ("=> \$\$L{$opt} = \"$arg\"\n")
582 if $debug;
583 ${$linkage{$opt}} = $arg;
584 }
585 }
586 elsif ( ref($linkage{$opt}) eq 'ARRAY' ) {
587 print STDERR ("=> push(\@{\$L{$opt}, \"$arg\")\n")
588 if $debug;
589 push (@{$linkage{$opt}}, $arg);
590 }
591 elsif ( ref($linkage{$opt}) eq 'HASH' ) {
592 print STDERR ("=> \$\$L{$opt}->{$key} = \"$arg\"\n")
593 if $debug;
594 $linkage{$opt}->{$key} = $arg;
595 }
596 elsif ( ref($linkage{$opt}) eq 'CODE' ) {
597 print STDERR ("=> &L{$opt}(\"$opt\"",
598 $ctl->[CTL_DEST] == CTL_DEST_HASH ? ", \"$key\"" : "",
599 ", \"$arg\")\n")
600 if $debug;
601 my $eval_error = do {
602 local $@;
603 local $SIG{__DIE__} = 'DEFAULT';
604 eval {
605 &{$linkage{$opt}}
606 (Getopt::Long::CallBack->new
607 (name => $opt,
608 ctl => $ctl,
609 opctl => \%opctl,
610 linkage => \%linkage,
611 prefix => $prefix,
612 ),
613 $ctl->[CTL_DEST] == CTL_DEST_HASH ? ($key) : (),
614 $arg);
615 };
616 $@;
617 };
618 print STDERR ("=> die($eval_error)\n")
619 if $debug && $eval_error ne '';
620 if ( $eval_error =~ /^!/ ) {
621 if ( $eval_error =~ /^!FINISH\b/ ) {
622 $goon = 0;
623 }
624 }
625 elsif ( $eval_error ne '' ) {
626 warn ($eval_error);
627 $error++;
628 }
629 }
630 else {
631 print STDERR ("Invalid REF type \"", ref($linkage{$opt}),
632 "\" in linkage\n");
633 die("Getopt::Long -- internal error!\n");
634 }
635 }
636 # No entry in linkage means entry in userlinkage.
637 elsif ( $ctl->[CTL_DEST] == CTL_DEST_ARRAY ) {
638 if ( defined $userlinkage->{$opt} ) {
639 print STDERR ("=> push(\@{\$L{$opt}}, \"$arg\")\n")
640 if $debug;
641 push (@{$userlinkage->{$opt}}, $arg);
642 }
643 else {
644 print STDERR ("=>\$L{$opt} = [\"$arg\"]\n")
645 if $debug;
646 $userlinkage->{$opt} = [$arg];
647 }
648 }
649 elsif ( $ctl->[CTL_DEST] == CTL_DEST_HASH ) {
650 if ( defined $userlinkage->{$opt} ) {
651 print STDERR ("=> \$L{$opt}->{$key} = \"$arg\"\n")
652 if $debug;
653 $userlinkage->{$opt}->{$key} = $arg;
654 }
655 else {
656 print STDERR ("=>\$L{$opt} = {$key => \"$arg\"}\n")
657 if $debug;
658 $userlinkage->{$opt} = {$key => $arg};
659 }
660 }
661 else {
662 if ( $ctl->[CTL_TYPE] eq '+' ) {
663 print STDERR ("=> \$L{$opt} += \"$arg\"\n")
664 if $debug;
665 if ( defined $userlinkage->{$opt} ) {
666 $userlinkage->{$opt} += $arg;
667 }
668 else {
669 $userlinkage->{$opt} = $arg;
670 }
671 }
672 else {
673 print STDERR ("=>\$L{$opt} = \"$arg\"\n") if $debug;
674 $userlinkage->{$opt} = $arg;
675 }
676 }
677  
678 $argcnt++;
679 last if $argcnt >= $ctl->[CTL_AMAX] && $ctl->[CTL_AMAX] != -1;
680 undef($arg);
681  
682 # Need more args?
683 if ( $argcnt < $ctl->[CTL_AMIN] ) {
684 if ( @$argv ) {
685 if ( ValidValue($ctl, $argv->[0], 1, $argend, $prefix) ) {
686 $arg = shift(@$argv);
687 if ( $ctl->[CTL_TYPE] =~ /^[iIo]$/ ) {
688 $arg =~ tr/_//d;
689 $arg = $ctl->[CTL_TYPE] eq 'o' && $arg =~ /^0/
690 ? oct($arg)
691 : 0+$arg
692 }
693 ($key,$arg) = $arg =~ /^([^=]+)=(.*)/
694 if $ctl->[CTL_DEST] == CTL_DEST_HASH;
695 next;
696 }
697 warn("Value \"$$argv[0]\" invalid for option $opt\n");
698 $error++;
699 }
700 else {
701 warn("Insufficient arguments for option $opt\n");
702 $error++;
703 }
704 }
705  
706 # Any more args?
707 if ( @$argv && ValidValue($ctl, $argv->[0], 0, $argend, $prefix) ) {
708 $arg = shift(@$argv);
709 if ( $ctl->[CTL_TYPE] =~ /^[iIo]$/ ) {
710 $arg =~ tr/_//d;
711 $arg = $ctl->[CTL_TYPE] eq 'o' && $arg =~ /^0/
712 ? oct($arg)
713 : 0+$arg
714 }
715 ($key,$arg) = $arg =~ /^([^=]+)=(.*)/
716 if $ctl->[CTL_DEST] == CTL_DEST_HASH;
717 next;
718 }
719 }
720 }
721  
722 # Not an option. Save it if we $PERMUTE and don't have a <>.
723 elsif ( $order == $PERMUTE ) {
724 # Try non-options call-back.
725 my $cb;
726 if ( defined ($cb = $linkage{'<>'}) ) {
727 print STDERR ("=> &L{$tryopt}(\"$tryopt\")\n")
728 if $debug;
729 my $eval_error = do {
730 local $@;
731 local $SIG{__DIE__} = 'DEFAULT';
732 eval {
733 # The arg to <> cannot be the CallBack object
734 # since it may be passed to other modules that
735 # get confused (e.g., Archive::Tar). Well,
736 # it's not relevant for this callback anyway.
737 &$cb($tryopt);
738 };
739 $@;
740 };
741 print STDERR ("=> die($eval_error)\n")
742 if $debug && $eval_error ne '';
743 if ( $eval_error =~ /^!/ ) {
744 if ( $eval_error =~ /^!FINISH\b/ ) {
745 $goon = 0;
746 }
747 }
748 elsif ( $eval_error ne '' ) {
749 warn ($eval_error);
750 $error++;
751 }
752 }
753 else {
754 print STDERR ("=> saving \"$tryopt\" ",
755 "(not an option, may permute)\n") if $debug;
756 push (@ret, $tryopt);
757 }
758 next;
759 }
760  
761 # ...otherwise, terminate.
762 else {
763 # Push this one back and exit.
764 unshift (@$argv, $tryopt);
765 return ($error == 0);
766 }
767  
768 }
769  
770 # Finish.
771 if ( @ret && $order == $PERMUTE ) {
772 # Push back accumulated arguments
773 print STDERR ("=> restoring \"", join('" "', @ret), "\"\n")
774 if $debug;
775 unshift (@$argv, @ret);
776 }
777  
778 return ($error == 0);
779 }
780  
781 # A readable representation of what's in an optbl.
782 sub OptCtl ($) {
783 my ($v) = @_;
784 my @v = map { defined($_) ? ($_) : ("<undef>") } @$v;
785 "[".
786 join(",",
787 "\"$v[CTL_TYPE]\"",
788 "\"$v[CTL_CNAME]\"",
789 "\"$v[CTL_DEFAULT]\"",
790 ("\$","\@","\%","\&")[$v[CTL_DEST] || 0],
791 $v[CTL_AMIN] || '',
792 $v[CTL_AMAX] || '',
793 # $v[CTL_RANGE] || '',
794 # $v[CTL_REPEAT] || '',
795 ). "]";
796 }
797  
798 # Parse an option specification and fill the tables.
799 sub ParseOptionSpec ($$) {
800 my ($opt, $opctl) = @_;
801  
802 # Match option spec.
803 if ( $opt !~ m;^
804 (
805 # Option name
806 (?: \w+[-\w]* )
807 # Alias names, or "?"
808 (?: \| (?: \? | \w[-\w]* ) )*
809 # Aliases
810 (?: \| (?: [^-|!+=:][^|!+=:]* )? )*
811 )?
812 (
813 # Either modifiers ...
814 [!+]
815 |
816 # ... or a value/dest/repeat specification
817 [=:] [ionfs] [@%]? (?: \{\d*,?\d*\} )?
818 |
819 # ... or an optional-with-default spec
820 : (?: -?\d+ | \+ ) [@%]?
821 )?
822 $;x ) {
823 return (undef, "Error in option spec: \"$opt\"\n");
824 }
825  
826 my ($names, $spec) = ($1, $2);
827 $spec = '' unless defined $spec;
828  
829 # $orig keeps track of the primary name the user specified.
830 # This name will be used for the internal or external linkage.
831 # In other words, if the user specifies "FoO|BaR", it will
832 # match any case combinations of 'foo' and 'bar', but if a global
833 # variable needs to be set, it will be $opt_FoO in the exact case
834 # as specified.
835 my $orig;
836  
837 my @names;
838 if ( defined $names ) {
839 @names = split (/\|/, $names);
840 $orig = $names[0];
841 }
842 else {
843 @names = ('');
844 $orig = '';
845 }
846  
847 # Construct the opctl entries.
848 my $entry;
849 if ( $spec eq '' || $spec eq '+' || $spec eq '!' ) {
850 # Fields are hard-wired here.
851 $entry = [$spec,$orig,undef,CTL_DEST_SCALAR,0,0];
852 }
853 elsif ( $spec =~ /^:(-?\d+|\+)([@%])?$/ ) {
854 my $def = $1;
855 my $dest = $2;
856 my $type = $def eq '+' ? 'I' : 'i';
857 $dest ||= '$';
858 $dest = $dest eq '@' ? CTL_DEST_ARRAY
859 : $dest eq '%' ? CTL_DEST_HASH : CTL_DEST_SCALAR;
860 # Fields are hard-wired here.
861 $entry = [$type,$orig,$def eq '+' ? undef : $def,
862 $dest,0,1];
863 }
864 else {
865 my ($mand, $type, $dest) =
866 $spec =~ /^([=:])([ionfs])([@%])?(\{(\d+)?(,)?(\d+)?\})?$/;
867 return (undef, "Cannot repeat while bundling: \"$opt\"\n")
868 if $bundling && defined($4);
869 my ($mi, $cm, $ma) = ($5, $6, $7);
870 return (undef, "{0} is useless in option spec: \"$opt\"\n")
871 if defined($mi) && !$mi && !defined($ma) && !defined($cm);
872  
873 $type = 'i' if $type eq 'n';
874 $dest ||= '$';
875 $dest = $dest eq '@' ? CTL_DEST_ARRAY
876 : $dest eq '%' ? CTL_DEST_HASH : CTL_DEST_SCALAR;
877 # Default minargs to 1/0 depending on mand status.
878 $mi = $mand eq '=' ? 1 : 0 unless defined $mi;
879 # Adjust mand status according to minargs.
880 $mand = $mi ? '=' : ':';
881 # Adjust maxargs.
882 $ma = $mi ? $mi : 1 unless defined $ma || defined $cm;
883 return (undef, "Max must be greater than zero in option spec: \"$opt\"\n")
884 if defined($ma) && !$ma;
885 return (undef, "Max less than min in option spec: \"$opt\"\n")
886 if defined($ma) && $ma < $mi;
887  
888 # Fields are hard-wired here.
889 $entry = [$type,$orig,undef,$dest,$mi,$ma||-1];
890 }
891  
892 # Process all names. First is canonical, the rest are aliases.
893 my $dups = '';
894 foreach ( @names ) {
895  
896 $_ = lc ($_)
897 if $ignorecase > (($bundling && length($_) == 1) ? 1 : 0);
898  
899 if ( exists $opctl->{$_} ) {
900 $dups .= "Duplicate specification \"$opt\" for option \"$_\"\n";
901 }
902  
903 if ( $spec eq '!' ) {
904 $opctl->{"no$_"} = $entry;
905 $opctl->{"no-$_"} = $entry;
906 $opctl->{$_} = [@$entry];
907 $opctl->{$_}->[CTL_TYPE] = '';
908 }
909 else {
910 $opctl->{$_} = $entry;
911 }
912 }
913  
914 if ( $dups && $^W ) {
915 foreach ( split(/\n+/, $dups) ) {
916 warn($_."\n");
917 }
918 }
919 ($names[0], $orig);
920 }
921  
922 # Option lookup.
923 sub FindOption ($$$$$) {
924  
925 # returns (1, $opt, $ctl, $arg, $key) if okay,
926 # returns (1, undef) if option in error,
927 # returns (0) otherwise.
928  
929 my ($argv, $prefix, $argend, $opt, $opctl) = @_;
930  
931 print STDERR ("=> find \"$opt\"\n") if $debug;
932  
933 return (0) unless defined($opt);
934 return (0) unless $opt =~ /^($prefix)(.*)$/s;
935 return (0) if $opt eq "-" && !defined $opctl->{''};
936  
937 $opt = substr( $opt, length($1) ); # retain taintedness
938 my $starter = $1;
939  
940 print STDERR ("=> split \"$starter\"+\"$opt\"\n") if $debug;
941  
942 my $optarg; # value supplied with --opt=value
943 my $rest; # remainder from unbundling
944  
945 # If it is a long option, it may include the value.
946 # With getopt_compat, only if not bundling.
947 if ( ($starter=~/^$longprefix$/
948 || ($getopt_compat && ($bundling == 0 || $bundling == 2)))
949 && (my $oppos = index($opt, '=', 1)) > 0) {
950 my $optorg = $opt;
951 $opt = substr($optorg, 0, $oppos);
952 $optarg = substr($optorg, $oppos + 1); # retain tainedness
953 print STDERR ("=> option \"", $opt,
954 "\", optarg = \"$optarg\"\n") if $debug;
955 }
956  
957 #### Look it up ###
958  
959 my $tryopt = $opt; # option to try
960  
961 if ( ( $bundling || $bundling_values ) && $starter eq '-' ) {
962  
963 # To try overrides, obey case ignore.
964 $tryopt = $ignorecase ? lc($opt) : $opt;
965  
966 # If bundling == 2, long options can override bundles.
967 if ( $bundling == 2 && length($tryopt) > 1
968 && defined ($opctl->{$tryopt}) ) {
969 print STDERR ("=> $starter$tryopt overrides unbundling\n")
970 if $debug;
971 }
972  
973 # If bundling_values, option may be followed by the value.
974 elsif ( $bundling_values ) {
975 $tryopt = $opt;
976 # Unbundle single letter option.
977 $rest = length ($tryopt) > 0 ? substr ($tryopt, 1) : '';
978 $tryopt = substr ($tryopt, 0, 1);
979 $tryopt = lc ($tryopt) if $ignorecase > 1;
980 print STDERR ("=> $starter$tryopt unbundled from ",
981 "$starter$tryopt$rest\n") if $debug;
982 # Whatever remains may not be considered an option.
983 $optarg = $rest eq '' ? undef : $rest;
984 $rest = undef;
985 }
986  
987 # Split off a single letter and leave the rest for
988 # further processing.
989 else {
990 $tryopt = $opt;
991 # Unbundle single letter option.
992 $rest = length ($tryopt) > 0 ? substr ($tryopt, 1) : '';
993 $tryopt = substr ($tryopt, 0, 1);
994 $tryopt = lc ($tryopt) if $ignorecase > 1;
995 print STDERR ("=> $starter$tryopt unbundled from ",
996 "$starter$tryopt$rest\n") if $debug;
997 $rest = undef unless $rest ne '';
998 }
999 }
1000  
1001 # Try auto-abbreviation.
1002 elsif ( $autoabbrev && $opt ne "" ) {
1003 # Sort the possible long option names.
1004 my @names = sort(keys (%$opctl));
1005 # Downcase if allowed.
1006 $opt = lc ($opt) if $ignorecase;
1007 $tryopt = $opt;
1008 # Turn option name into pattern.
1009 my $pat = quotemeta ($opt);
1010 # Look up in option names.
1011 my @hits = grep (/^$pat/, @names);
1012 print STDERR ("=> ", scalar(@hits), " hits (@hits) with \"$pat\" ",
1013 "out of ", scalar(@names), "\n") if $debug;
1014  
1015 # Check for ambiguous results.
1016 unless ( (@hits <= 1) || (grep ($_ eq $opt, @hits) == 1) ) {
1017 # See if all matches are for the same option.
1018 my %hit;
1019 foreach ( @hits ) {
1020 my $hit = $opctl->{$_}->[CTL_CNAME]
1021 if defined $opctl->{$_}->[CTL_CNAME];
1022 $hit = "no" . $hit if $opctl->{$_}->[CTL_TYPE] eq '!';
1023 $hit{$hit} = 1;
1024 }
1025 # Remove auto-supplied options (version, help).
1026 if ( keys(%hit) == 2 ) {
1027 if ( $auto_version && exists($hit{version}) ) {
1028 delete $hit{version};
1029 }
1030 elsif ( $auto_help && exists($hit{help}) ) {
1031 delete $hit{help};
1032 }
1033 }
1034 # Now see if it really is ambiguous.
1035 unless ( keys(%hit) == 1 ) {
1036 return (0) if $passthrough;
1037 warn ("Option ", $opt, " is ambiguous (",
1038 join(", ", @hits), ")\n");
1039 $error++;
1040 return (1, undef);
1041 }
1042 @hits = keys(%hit);
1043 }
1044  
1045 # Complete the option name, if appropriate.
1046 if ( @hits == 1 && $hits[0] ne $opt ) {
1047 $tryopt = $hits[0];
1048 $tryopt = lc ($tryopt) if $ignorecase;
1049 print STDERR ("=> option \"$opt\" -> \"$tryopt\"\n")
1050 if $debug;
1051 }
1052 }
1053  
1054 # Map to all lowercase if ignoring case.
1055 elsif ( $ignorecase ) {
1056 $tryopt = lc ($opt);
1057 }
1058  
1059 # Check validity by fetching the info.
1060 my $ctl = $opctl->{$tryopt};
1061 unless ( defined $ctl ) {
1062 return (0) if $passthrough;
1063 # Pretend one char when bundling.
1064 if ( $bundling == 1 && length($starter) == 1 ) {
1065 $opt = substr($opt,0,1);
1066 unshift (@$argv, $starter.$rest) if defined $rest;
1067 }
1068 if ( $opt eq "" ) {
1069 warn ("Missing option after ", $starter, "\n");
1070 }
1071 else {
1072 warn ("Unknown option: ", $opt, "\n");
1073 }
1074 $error++;
1075 return (1, undef);
1076 }
1077 # Apparently valid.
1078 $opt = $tryopt;
1079 print STDERR ("=> found ", OptCtl($ctl),
1080 " for \"", $opt, "\"\n") if $debug;
1081  
1082 #### Determine argument status ####
1083  
1084 # If it is an option w/o argument, we're almost finished with it.
1085 my $type = $ctl->[CTL_TYPE];
1086 my $arg;
1087  
1088 if ( $type eq '' || $type eq '!' || $type eq '+' ) {
1089 if ( defined $optarg ) {
1090 return (0) if $passthrough;
1091 warn ("Option ", $opt, " does not take an argument\n");
1092 $error++;
1093 undef $opt;
1094 undef $optarg if $bundling_values;
1095 }
1096 elsif ( $type eq '' || $type eq '+' ) {
1097 # Supply explicit value.
1098 $arg = 1;
1099 }
1100 else {
1101 $opt =~ s/^no-?//i; # strip NO prefix
1102 $arg = 0; # supply explicit value
1103 }
1104 unshift (@$argv, $starter.$rest) if defined $rest;
1105 return (1, $opt, $ctl, $arg);
1106 }
1107  
1108 # Get mandatory status and type info.
1109 my $mand = $ctl->[CTL_AMIN];
1110  
1111 # Check if there is an option argument available.
1112 if ( $gnu_compat ) {
1113 my $optargtype = 0; # 0 = none, 1 = empty, 2 = nonempty
1114 $optargtype = ( !defined($optarg) ? 0 : ( (length($optarg) == 0) ? 1 : 2 ) );
1115 return (1, $opt, $ctl, defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] : undef)
1116 if (($optargtype == 0) && !$mand);
1117 return (1, $opt, $ctl, $type eq 's' ? '' : 0)
1118 if $optargtype == 1; # --foo= -> return nothing
1119 }
1120  
1121 # Check if there is an option argument available.
1122 if ( defined $optarg
1123 ? ($optarg eq '')
1124 : !(defined $rest || @$argv > 0) ) {
1125 # Complain if this option needs an argument.
1126 # if ( $mand && !($type eq 's' ? defined($optarg) : 0) ) {
1127 if ( $mand ) {
1128 return (0) if $passthrough;
1129 warn ("Option ", $opt, " requires an argument\n");
1130 $error++;
1131 return (1, undef);
1132 }
1133 if ( $type eq 'I' ) {
1134 # Fake incremental type.
1135 my @c = @$ctl;
1136 $c[CTL_TYPE] = '+';
1137 return (1, $opt, \@c, 1);
1138 }
1139 return (1, $opt, $ctl,
1140 defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] :
1141 $type eq 's' ? '' : 0);
1142 }
1143  
1144 # Get (possibly optional) argument.
1145 $arg = (defined $rest ? $rest
1146 : (defined $optarg ? $optarg : shift (@$argv)));
1147  
1148 # Get key if this is a "name=value" pair for a hash option.
1149 my $key;
1150 if ($ctl->[CTL_DEST] == CTL_DEST_HASH && defined $arg) {
1151 ($key, $arg) = ($arg =~ /^([^=]*)=(.*)$/s) ? ($1, $2)
1152 : ($arg, defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] :
1153 ($mand ? undef : ($type eq 's' ? "" : 1)));
1154 if (! defined $arg) {
1155 warn ("Option $opt, key \"$key\", requires a value\n");
1156 $error++;
1157 # Push back.
1158 unshift (@$argv, $starter.$rest) if defined $rest;
1159 return (1, undef);
1160 }
1161 }
1162  
1163 #### Check if the argument is valid for this option ####
1164  
1165 my $key_valid = $ctl->[CTL_DEST] == CTL_DEST_HASH ? "[^=]+=" : "";
1166  
1167 if ( $type eq 's' ) { # string
1168 # A mandatory string takes anything.
1169 return (1, $opt, $ctl, $arg, $key) if $mand;
1170  
1171 # Same for optional string as a hash value
1172 return (1, $opt, $ctl, $arg, $key)
1173 if $ctl->[CTL_DEST] == CTL_DEST_HASH;
1174  
1175 # An optional string takes almost anything.
1176 return (1, $opt, $ctl, $arg, $key)
1177 if defined $optarg || defined $rest;
1178 return (1, $opt, $ctl, $arg, $key) if $arg eq "-"; # ??
1179  
1180 # Check for option or option list terminator.
1181 if ($arg eq $argend ||
1182 $arg =~ /^$prefix.+/) {
1183 # Push back.
1184 unshift (@$argv, $arg);
1185 # Supply empty value.
1186 $arg = '';
1187 }
1188 }
1189  
1190 elsif ( $type eq 'i' # numeric/integer
1191 || $type eq 'I' # numeric/integer w/ incr default
1192 || $type eq 'o' ) { # dec/oct/hex/bin value
1193  
1194 my $o_valid = $type eq 'o' ? PAT_XINT : PAT_INT;
1195  
1196 if ( $bundling && defined $rest
1197 && $rest =~ /^($key_valid)($o_valid)(.*)$/si ) {
1198 ($key, $arg, $rest) = ($1, $2, $+);
1199 chop($key) if $key;
1200 $arg = ($type eq 'o' && $arg =~ /^0/) ? oct($arg) : 0+$arg;
1201 unshift (@$argv, $starter.$rest) if defined $rest && $rest ne '';
1202 }
1203 elsif ( $arg =~ /^$o_valid$/si ) {
1204 $arg =~ tr/_//d;
1205 $arg = ($type eq 'o' && $arg =~ /^0/) ? oct($arg) : 0+$arg;
1206 }
1207 else {
1208 if ( defined $optarg || $mand ) {
1209 if ( $passthrough ) {
1210 unshift (@$argv, defined $rest ? $starter.$rest : $arg)
1211 unless defined $optarg;
1212 return (0);
1213 }
1214 warn ("Value \"", $arg, "\" invalid for option ",
1215 $opt, " (",
1216 $type eq 'o' ? "extended " : '',
1217 "number expected)\n");
1218 $error++;
1219 # Push back.
1220 unshift (@$argv, $starter.$rest) if defined $rest;
1221 return (1, undef);
1222 }
1223 else {
1224 # Push back.
1225 unshift (@$argv, defined $rest ? $starter.$rest : $arg);
1226 if ( $type eq 'I' ) {
1227 # Fake incremental type.
1228 my @c = @$ctl;
1229 $c[CTL_TYPE] = '+';
1230 return (1, $opt, \@c, 1);
1231 }
1232 # Supply default value.
1233 $arg = defined($ctl->[CTL_DEFAULT]) ? $ctl->[CTL_DEFAULT] : 0;
1234 }
1235 }
1236 }
1237  
1238 elsif ( $type eq 'f' ) { # real number, int is also ok
1239 my $o_valid = PAT_FLOAT;
1240 if ( $bundling && defined $rest &&
1241 $rest =~ /^($key_valid)($o_valid)(.*)$/s ) {
1242 $arg =~ tr/_//d;
1243 ($key, $arg, $rest) = ($1, $2, $+);
1244 chop($key) if $key;
1245 unshift (@$argv, $starter.$rest) if defined $rest && $rest ne '';
1246 }
1247 elsif ( $arg =~ /^$o_valid$/ ) {
1248 $arg =~ tr/_//d;
1249 }
1250 else {
1251 if ( defined $optarg || $mand ) {
1252 if ( $passthrough ) {
1253 unshift (@$argv, defined $rest ? $starter.$rest : $arg)
1254 unless defined $optarg;
1255 return (0);
1256 }
1257 warn ("Value \"", $arg, "\" invalid for option ",
1258 $opt, " (real number expected)\n");
1259 $error++;
1260 # Push back.
1261 unshift (@$argv, $starter.$rest) if defined $rest;
1262 return (1, undef);
1263 }
1264 else {
1265 # Push back.
1266 unshift (@$argv, defined $rest ? $starter.$rest : $arg);
1267 # Supply default value.
1268 $arg = 0.0;
1269 }
1270 }
1271 }
1272 else {
1273 die("Getopt::Long internal error (Can't happen)\n");
1274 }
1275 return (1, $opt, $ctl, $arg, $key);
1276 }
1277  
1278 sub ValidValue ($$$$$) {
1279 my ($ctl, $arg, $mand, $argend, $prefix) = @_;
1280  
1281 if ( $ctl->[CTL_DEST] == CTL_DEST_HASH ) {
1282 return 0 unless $arg =~ /[^=]+=(.*)/;
1283 $arg = $1;
1284 }
1285  
1286 my $type = $ctl->[CTL_TYPE];
1287  
1288 if ( $type eq 's' ) { # string
1289 # A mandatory string takes anything.
1290 return (1) if $mand;
1291  
1292 return (1) if $arg eq "-";
1293  
1294 # Check for option or option list terminator.
1295 return 0 if $arg eq $argend || $arg =~ /^$prefix.+/;
1296 return 1;
1297 }
1298  
1299 elsif ( $type eq 'i' # numeric/integer
1300 || $type eq 'I' # numeric/integer w/ incr default
1301 || $type eq 'o' ) { # dec/oct/hex/bin value
1302  
1303 my $o_valid = $type eq 'o' ? PAT_XINT : PAT_INT;
1304 return $arg =~ /^$o_valid$/si;
1305 }
1306  
1307 elsif ( $type eq 'f' ) { # real number, int is also ok
1308 my $o_valid = PAT_FLOAT;
1309 return $arg =~ /^$o_valid$/;
1310 }
1311 die("ValidValue: Cannot happen\n");
1312 }
1313  
1314 # Getopt::Long Configuration.
1315 sub Configure (@) {
1316 my (@options) = @_;
1317  
1318 my $prevconfig =
1319 [ $error, $debug, $major_version, $minor_version, $caller,
1320 $autoabbrev, $getopt_compat, $ignorecase, $bundling, $order,
1321 $gnu_compat, $passthrough, $genprefix, $auto_version, $auto_help,
1322 $longprefix, $bundling_values ];
1323  
1324 if ( ref($options[0]) eq 'ARRAY' ) {
1325 ( $error, $debug, $major_version, $minor_version, $caller,
1326 $autoabbrev, $getopt_compat, $ignorecase, $bundling, $order,
1327 $gnu_compat, $passthrough, $genprefix, $auto_version, $auto_help,
1328 $longprefix, $bundling_values ) = @{shift(@options)};
1329 }
1330  
1331 my $opt;
1332 foreach $opt ( @options ) {
1333 my $try = lc ($opt);
1334 my $action = 1;
1335 if ( $try =~ /^no_?(.*)$/s ) {
1336 $action = 0;
1337 $try = $+;
1338 }
1339 if ( ($try eq 'default' or $try eq 'defaults') && $action ) {
1340 ConfigDefaults ();
1341 }
1342 elsif ( ($try eq 'posix_default' or $try eq 'posix_defaults') ) {
1343 local $ENV{POSIXLY_CORRECT};
1344 $ENV{POSIXLY_CORRECT} = 1 if $action;
1345 ConfigDefaults ();
1346 }
1347 elsif ( $try eq 'auto_abbrev' or $try eq 'autoabbrev' ) {
1348 $autoabbrev = $action;
1349 }
1350 elsif ( $try eq 'getopt_compat' ) {
1351 $getopt_compat = $action;
1352 $genprefix = $action ? "(--|-|\\+)" : "(--|-)";
1353 }
1354 elsif ( $try eq 'gnu_getopt' ) {
1355 if ( $action ) {
1356 $gnu_compat = 1;
1357 $bundling = 1;
1358 $getopt_compat = 0;
1359 $genprefix = "(--|-)";
1360 $order = $PERMUTE;
1361 $bundling_values = 0;
1362 }
1363 }
1364 elsif ( $try eq 'gnu_compat' ) {
1365 $gnu_compat = $action;
1366 $bundling = 0;
1367 $bundling_values = 1;
1368 }
1369 elsif ( $try =~ /^(auto_?)?version$/ ) {
1370 $auto_version = $action;
1371 }
1372 elsif ( $try =~ /^(auto_?)?help$/ ) {
1373 $auto_help = $action;
1374 }
1375 elsif ( $try eq 'ignorecase' or $try eq 'ignore_case' ) {
1376 $ignorecase = $action;
1377 }
1378 elsif ( $try eq 'ignorecase_always' or $try eq 'ignore_case_always' ) {
1379 $ignorecase = $action ? 2 : 0;
1380 }
1381 elsif ( $try eq 'bundling' ) {
1382 $bundling = $action;
1383 $bundling_values = 0 if $action;
1384 }
1385 elsif ( $try eq 'bundling_override' ) {
1386 $bundling = $action ? 2 : 0;
1387 $bundling_values = 0 if $action;
1388 }
1389 elsif ( $try eq 'bundling_values' ) {
1390 $bundling_values = $action;
1391 $bundling = 0 if $action;
1392 }
1393 elsif ( $try eq 'require_order' ) {
1394 $order = $action ? $REQUIRE_ORDER : $PERMUTE;
1395 }
1396 elsif ( $try eq 'permute' ) {
1397 $order = $action ? $PERMUTE : $REQUIRE_ORDER;
1398 }
1399 elsif ( $try eq 'pass_through' or $try eq 'passthrough' ) {
1400 $passthrough = $action;
1401 }
1402 elsif ( $try =~ /^prefix=(.+)$/ && $action ) {
1403 $genprefix = $1;
1404 # Turn into regexp. Needs to be parenthesized!
1405 $genprefix = "(" . quotemeta($genprefix) . ")";
1406 eval { '' =~ /$genprefix/; };
1407 die("Getopt::Long: invalid pattern \"$genprefix\"\n") if $@;
1408 }
1409 elsif ( $try =~ /^prefix_pattern=(.+)$/ && $action ) {
1410 $genprefix = $1;
1411 # Parenthesize if needed.
1412 $genprefix = "(" . $genprefix . ")"
1413 unless $genprefix =~ /^\(.*\)$/;
1414 eval { '' =~ m"$genprefix"; };
1415 die("Getopt::Long: invalid pattern \"$genprefix\"\n") if $@;
1416 }
1417 elsif ( $try =~ /^long_prefix_pattern=(.+)$/ && $action ) {
1418 $longprefix = $1;
1419 # Parenthesize if needed.
1420 $longprefix = "(" . $longprefix . ")"
1421 unless $longprefix =~ /^\(.*\)$/;
1422 eval { '' =~ m"$longprefix"; };
1423 die("Getopt::Long: invalid long prefix pattern \"$longprefix\"\n") if $@;
1424 }
1425 elsif ( $try eq 'debug' ) {
1426 $debug = $action;
1427 }
1428 else {
1429 die("Getopt::Long: unknown or erroneous config parameter \"$opt\"\n")
1430 }
1431 }
1432 $prevconfig;
1433 }
1434  
1435 # Deprecated name.
1436 sub config (@) {
1437 Configure (@_);
1438 }
1439  
1440 # Issue a standard message for --version.
1441 #
1442 # The arguments are mostly the same as for Pod::Usage::pod2usage:
1443 #
1444 # - a number (exit value)
1445 # - a string (lead in message)
1446 # - a hash with options. See Pod::Usage for details.
1447 #
1448 sub VersionMessage(@) {
1449 # Massage args.
1450 my $pa = setup_pa_args("version", @_);
1451  
1452 my $v = $main::VERSION;
1453 my $fh = $pa->{-output} ||
1454 ( ($pa->{-exitval} eq "NOEXIT" || $pa->{-exitval} < 2) ? \*STDOUT : \*STDERR );
1455  
1456 print $fh (defined($pa->{-message}) ? $pa->{-message} : (),
1457 $0, defined $v ? " version $v" : (),
1458 "\n",
1459 "(", __PACKAGE__, "::", "GetOptions",
1460 " version ",
1461 defined($Getopt::Long::VERSION_STRING)
1462 ? $Getopt::Long::VERSION_STRING : $VERSION, ";",
1463 " Perl version ",
1464 $] >= 5.006 ? sprintf("%vd", $^V) : $],
1465 ")\n");
1466 exit($pa->{-exitval}) unless $pa->{-exitval} eq "NOEXIT";
1467 }
1468  
1469 # Issue a standard message for --help.
1470 #
1471 # The arguments are the same as for Pod::Usage::pod2usage:
1472 #
1473 # - a number (exit value)
1474 # - a string (lead in message)
1475 # - a hash with options. See Pod::Usage for details.
1476 #
1477 sub HelpMessage(@) {
1478 eval {
1479 require Pod::Usage;
1480 import Pod::Usage;
1481 1;
1482 } || die("Cannot provide help: cannot load Pod::Usage\n");
1483  
1484 # Note that pod2usage will issue a warning if -exitval => NOEXIT.
1485 pod2usage(setup_pa_args("help", @_));
1486  
1487 }
1488  
1489 # Helper routine to set up a normalized hash ref to be used as
1490 # argument to pod2usage.
1491 sub setup_pa_args($@) {
1492 my $tag = shift; # who's calling
1493  
1494 # If called by direct binding to an option, it will get the option
1495 # name and value as arguments. Remove these, if so.
1496 @_ = () if @_ == 2 && $_[0] eq $tag;
1497  
1498 my $pa;
1499 if ( @_ > 1 ) {
1500 $pa = { @_ };
1501 }
1502 else {
1503 $pa = shift || {};
1504 }
1505  
1506 # At this point, $pa can be a number (exit value), string
1507 # (message) or hash with options.
1508  
1509 if ( UNIVERSAL::isa($pa, 'HASH') ) {
1510 # Get rid of -msg vs. -message ambiguity.
1511 $pa->{-message} = $pa->{-msg};
1512 delete($pa->{-msg});
1513 }
1514 elsif ( $pa =~ /^-?\d+$/ ) {
1515 $pa = { -exitval => $pa };
1516 }
1517 else {
1518 $pa = { -message => $pa };
1519 }
1520  
1521 # These are _our_ defaults.
1522 $pa->{-verbose} = 0 unless exists($pa->{-verbose});
1523 $pa->{-exitval} = 0 unless exists($pa->{-exitval});
1524 $pa;
1525 }
1526  
1527 # Sneak way to know what version the user requested.
1528 sub VERSION {
1529 $requested_version = $_[1];
1530 shift->SUPER::VERSION(@_);
1531 }
1532  
1533 package Getopt::Long::CallBack;
1534  
1535 sub new {
1536 my ($pkg, %atts) = @_;
1537 bless { %atts }, $pkg;
1538 }
1539  
1540 sub name {
1541 my $self = shift;
1542 ''.$self->{name};
1543 }
1544  
1545 use overload
1546 # Treat this object as an ordinary string for legacy API.
1547 '""' => \&name,
1548 fallback => 1;
1549  
1550 1;
1551  
1552 ################ Documentation ################
1553  
1554 =head1 NAME
1555  
1556 Getopt::Long - Extended processing of command line options
1557  
1558 =head1 SYNOPSIS
1559  
1560 use Getopt::Long;
1561 my $data = "file.dat";
1562 my $length = 24;
1563 my $verbose;
1564 GetOptions ("length=i" => \$length, # numeric
1565 "file=s" => \$data, # string
1566 "verbose" => \$verbose) # flag
1567 or die("Error in command line arguments\n");
1568  
1569 =head1 DESCRIPTION
1570  
1571 The Getopt::Long module implements an extended getopt function called
1572 GetOptions(). It parses the command line from C<@ARGV>, recognizing
1573 and removing specified options and their possible values.
1574  
1575 This function adheres to the POSIX syntax for command
1576 line options, with GNU extensions. In general, this means that options
1577 have long names instead of single letters, and are introduced with a
1578 double dash "--". Support for bundling of command line options, as was
1579 the case with the more traditional single-letter approach, is provided
1580 but not enabled by default.
1581  
1582 =head1 Command Line Options, an Introduction
1583  
1584 Command line operated programs traditionally take their arguments from
1585 the command line, for example filenames or other information that the
1586 program needs to know. Besides arguments, these programs often take
1587 command line I<options> as well. Options are not necessary for the
1588 program to work, hence the name 'option', but are used to modify its
1589 default behaviour. For example, a program could do its job quietly,
1590 but with a suitable option it could provide verbose information about
1591 what it did.
1592  
1593 Command line options come in several flavours. Historically, they are
1594 preceded by a single dash C<->, and consist of a single letter.
1595  
1596 -l -a -c
1597  
1598 Usually, these single-character options can be bundled:
1599  
1600 -lac
1601  
1602 Options can have values, the value is placed after the option
1603 character. Sometimes with whitespace in between, sometimes not:
1604  
1605 -s 24 -s24
1606  
1607 Due to the very cryptic nature of these options, another style was
1608 developed that used long names. So instead of a cryptic C<-l> one
1609 could use the more descriptive C<--long>. To distinguish between a
1610 bundle of single-character options and a long one, two dashes are used
1611 to precede the option name. Early implementations of long options used
1612 a plus C<+> instead. Also, option values could be specified either
1613 like
1614  
1615 --size=24
1616  
1617 or
1618  
1619 --size 24
1620  
1621 The C<+> form is now obsolete and strongly deprecated.
1622  
1623 =head1 Getting Started with Getopt::Long
1624  
1625 Getopt::Long is the Perl5 successor of C<newgetopt.pl>. This was the
1626 first Perl module that provided support for handling the new style of
1627 command line options, in particular long option names, hence the Perl5
1628 name Getopt::Long. This module also supports single-character options
1629 and bundling.
1630  
1631 To use Getopt::Long from a Perl program, you must include the
1632 following line in your Perl program:
1633  
1634 use Getopt::Long;
1635  
1636 This will load the core of the Getopt::Long module and prepare your
1637 program for using it. Most of the actual Getopt::Long code is not
1638 loaded until you really call one of its functions.
1639  
1640 In the default configuration, options names may be abbreviated to
1641 uniqueness, case does not matter, and a single dash is sufficient,
1642 even for long option names. Also, options may be placed between
1643 non-option arguments. See L<Configuring Getopt::Long> for more
1644 details on how to configure Getopt::Long.
1645  
1646 =head2 Simple options
1647  
1648 The most simple options are the ones that take no values. Their mere
1649 presence on the command line enables the option. Popular examples are:
1650  
1651 --all --verbose --quiet --debug
1652  
1653 Handling simple options is straightforward:
1654  
1655 my $verbose = ''; # option variable with default value (false)
1656 my $all = ''; # option variable with default value (false)
1657 GetOptions ('verbose' => \$verbose, 'all' => \$all);
1658  
1659 The call to GetOptions() parses the command line arguments that are
1660 present in C<@ARGV> and sets the option variable to the value C<1> if
1661 the option did occur on the command line. Otherwise, the option
1662 variable is not touched. Setting the option value to true is often
1663 called I<enabling> the option.
1664  
1665 The option name as specified to the GetOptions() function is called
1666 the option I<specification>. Later we'll see that this specification
1667 can contain more than just the option name. The reference to the
1668 variable is called the option I<destination>.
1669  
1670 GetOptions() will return a true value if the command line could be
1671 processed successfully. Otherwise, it will write error messages using
1672 die() and warn(), and return a false result.
1673  
1674 =head2 A little bit less simple options
1675  
1676 Getopt::Long supports two useful variants of simple options:
1677 I<negatable> options and I<incremental> options.
1678  
1679 A negatable option is specified with an exclamation mark C<!> after the
1680 option name:
1681  
1682 my $verbose = ''; # option variable with default value (false)
1683 GetOptions ('verbose!' => \$verbose);
1684  
1685 Now, using C<--verbose> on the command line will enable C<$verbose>,
1686 as expected. But it is also allowed to use C<--noverbose>, which will
1687 disable C<$verbose> by setting its value to C<0>. Using a suitable
1688 default value, the program can find out whether C<$verbose> is false
1689 by default, or disabled by using C<--noverbose>.
1690  
1691 An incremental option is specified with a plus C<+> after the
1692 option name:
1693  
1694 my $verbose = ''; # option variable with default value (false)
1695 GetOptions ('verbose+' => \$verbose);
1696  
1697 Using C<--verbose> on the command line will increment the value of
1698 C<$verbose>. This way the program can keep track of how many times the
1699 option occurred on the command line. For example, each occurrence of
1700 C<--verbose> could increase the verbosity level of the program.
1701  
1702 =head2 Mixing command line option with other arguments
1703  
1704 Usually programs take command line options as well as other arguments,
1705 for example, file names. It is good practice to always specify the
1706 options first, and the other arguments last. Getopt::Long will,
1707 however, allow the options and arguments to be mixed and 'filter out'
1708 all the options before passing the rest of the arguments to the
1709 program. To stop Getopt::Long from processing further arguments,
1710 insert a double dash C<--> on the command line:
1711  
1712 --size 24 -- --all
1713  
1714 In this example, C<--all> will I<not> be treated as an option, but
1715 passed to the program unharmed, in C<@ARGV>.
1716  
1717 =head2 Options with values
1718  
1719 For options that take values it must be specified whether the option
1720 value is required or not, and what kind of value the option expects.
1721  
1722 Three kinds of values are supported: integer numbers, floating point
1723 numbers, and strings.
1724  
1725 If the option value is required, Getopt::Long will take the
1726 command line argument that follows the option and assign this to the
1727 option variable. If, however, the option value is specified as
1728 optional, this will only be done if that value does not look like a
1729 valid command line option itself.
1730  
1731 my $tag = ''; # option variable with default value
1732 GetOptions ('tag=s' => \$tag);
1733  
1734 In the option specification, the option name is followed by an equals
1735 sign C<=> and the letter C<s>. The equals sign indicates that this
1736 option requires a value. The letter C<s> indicates that this value is
1737 an arbitrary string. Other possible value types are C<i> for integer
1738 values, and C<f> for floating point values. Using a colon C<:> instead
1739 of the equals sign indicates that the option value is optional. In
1740 this case, if no suitable value is supplied, string valued options get
1741 an empty string C<''> assigned, while numeric options are set to C<0>.
1742  
1743 =head2 Options with multiple values
1744  
1745 Options sometimes take several values. For example, a program could
1746 use multiple directories to search for library files:
1747  
1748 --library lib/stdlib --library lib/extlib
1749  
1750 To accomplish this behaviour, simply specify an array reference as the
1751 destination for the option:
1752  
1753 GetOptions ("library=s" => \@libfiles);
1754  
1755 Alternatively, you can specify that the option can have multiple
1756 values by adding a "@", and pass a scalar reference as the
1757 destination:
1758  
1759 GetOptions ("library=s@" => \$libfiles);
1760  
1761 Used with the example above, C<@libfiles> (or C<@$libfiles>) would
1762 contain two strings upon completion: C<"lib/stdlib"> and
1763 C<"lib/extlib">, in that order. It is also possible to specify that
1764 only integer or floating point numbers are acceptable values.
1765  
1766 Often it is useful to allow comma-separated lists of values as well as
1767 multiple occurrences of the options. This is easy using Perl's split()
1768 and join() operators:
1769  
1770 GetOptions ("library=s" => \@libfiles);
1771 @libfiles = split(/,/,join(',',@libfiles));
1772  
1773 Of course, it is important to choose the right separator string for
1774 each purpose.
1775  
1776 Warning: What follows is an experimental feature.
1777  
1778 Options can take multiple values at once, for example
1779  
1780 --coordinates 52.2 16.4 --rgbcolor 255 255 149
1781  
1782 This can be accomplished by adding a repeat specifier to the option
1783 specification. Repeat specifiers are very similar to the C<{...}>
1784 repeat specifiers that can be used with regular expression patterns.
1785 For example, the above command line would be handled as follows:
1786  
1787 GetOptions('coordinates=f{2}' => \@coor, 'rgbcolor=i{3}' => \@color);
1788  
1789 The destination for the option must be an array or array reference.
1790  
1791 It is also possible to specify the minimal and maximal number of
1792 arguments an option takes. C<foo=s{2,4}> indicates an option that
1793 takes at least two and at most 4 arguments. C<foo=s{1,}> indicates one
1794 or more values; C<foo:s{,}> indicates zero or more option values.
1795  
1796 =head2 Options with hash values
1797  
1798 If the option destination is a reference to a hash, the option will
1799 take, as value, strings of the form I<key>C<=>I<value>. The value will
1800 be stored with the specified key in the hash.
1801  
1802 GetOptions ("define=s" => \%defines);
1803  
1804 Alternatively you can use:
1805  
1806 GetOptions ("define=s%" => \$defines);
1807  
1808 When used with command line options:
1809  
1810 --define os=linux --define vendor=redhat
1811  
1812 the hash C<%defines> (or C<%$defines>) will contain two keys, C<"os">
1813 with value C<"linux"> and C<"vendor"> with value C<"redhat">. It is
1814 also possible to specify that only integer or floating point numbers
1815 are acceptable values. The keys are always taken to be strings.
1816  
1817 =head2 User-defined subroutines to handle options
1818  
1819 Ultimate control over what should be done when (actually: each time)
1820 an option is encountered on the command line can be achieved by
1821 designating a reference to a subroutine (or an anonymous subroutine)
1822 as the option destination. When GetOptions() encounters the option, it
1823 will call the subroutine with two or three arguments. The first
1824 argument is the name of the option. (Actually, it is an object that
1825 stringifies to the name of the option.) For a scalar or array destination,
1826 the second argument is the value to be stored. For a hash destination,
1827 the second argument is the key to the hash, and the third argument
1828 the value to be stored. It is up to the subroutine to store the value,
1829 or do whatever it thinks is appropriate.
1830  
1831 A trivial application of this mechanism is to implement options that
1832 are related to each other. For example:
1833  
1834 my $verbose = ''; # option variable with default value (false)
1835 GetOptions ('verbose' => \$verbose,
1836 'quiet' => sub { $verbose = 0 });
1837  
1838 Here C<--verbose> and C<--quiet> control the same variable
1839 C<$verbose>, but with opposite values.
1840  
1841 If the subroutine needs to signal an error, it should call die() with
1842 the desired error message as its argument. GetOptions() will catch the
1843 die(), issue the error message, and record that an error result must
1844 be returned upon completion.
1845  
1846 If the text of the error message starts with an exclamation mark C<!>
1847 it is interpreted specially by GetOptions(). There is currently one
1848 special command implemented: C<die("!FINISH")> will cause GetOptions()
1849 to stop processing options, as if it encountered a double dash C<-->.
1850  
1851 In version 2.37 the first argument to the callback function was
1852 changed from string to object. This was done to make room for
1853 extensions and more detailed control. The object stringifies to the
1854 option name so this change should not introduce compatibility
1855 problems.
1856  
1857 Here is an example of how to access the option name and value from within
1858 a subroutine:
1859  
1860 GetOptions ('opt=i' => \&handler);
1861 sub handler {
1862 my ($opt_name, $opt_value) = @_;
1863 print("Option name is $opt_name and value is $opt_value\n");
1864 }
1865  
1866 =head2 Options with multiple names
1867  
1868 Often it is user friendly to supply alternate mnemonic names for
1869 options. For example C<--height> could be an alternate name for
1870 C<--length>. Alternate names can be included in the option
1871 specification, separated by vertical bar C<|> characters. To implement
1872 the above example:
1873  
1874 GetOptions ('length|height=f' => \$length);
1875  
1876 The first name is called the I<primary> name, the other names are
1877 called I<aliases>. When using a hash to store options, the key will
1878 always be the primary name.
1879  
1880 Multiple alternate names are possible.
1881  
1882 =head2 Case and abbreviations
1883  
1884 Without additional configuration, GetOptions() will ignore the case of
1885 option names, and allow the options to be abbreviated to uniqueness.
1886  
1887 GetOptions ('length|height=f' => \$length, "head" => \$head);
1888  
1889 This call will allow C<--l> and C<--L> for the length option, but
1890 requires a least C<--hea> and C<--hei> for the head and height options.
1891  
1892 =head2 Summary of Option Specifications
1893  
1894 Each option specifier consists of two parts: the name specification
1895 and the argument specification.
1896  
1897 The name specification contains the name of the option, optionally
1898 followed by a list of alternative names separated by vertical bar
1899 characters.
1900  
1901 length option name is "length"
1902 length|size|l name is "length", aliases are "size" and "l"
1903  
1904 The argument specification is optional. If omitted, the option is
1905 considered boolean, a value of 1 will be assigned when the option is
1906 used on the command line.
1907  
1908 The argument specification can be
1909  
1910 =over 4
1911  
1912 =item !
1913  
1914 The option does not take an argument and may be negated by prefixing
1915 it with "no" or "no-". E.g. C<"foo!"> will allow C<--foo> (a value of
1916 1 will be assigned) as well as C<--nofoo> and C<--no-foo> (a value of
1917 0 will be assigned). If the option has aliases, this applies to the
1918 aliases as well.
1919  
1920 Using negation on a single letter option when bundling is in effect is
1921 pointless and will result in a warning.
1922  
1923 =item +
1924  
1925 The option does not take an argument and will be incremented by 1
1926 every time it appears on the command line. E.g. C<"more+">, when used
1927 with C<--more --more --more>, will increment the value three times,
1928 resulting in a value of 3 (provided it was 0 or undefined at first).
1929  
1930 The C<+> specifier is ignored if the option destination is not a scalar.
1931  
1932 =item = I<type> [ I<desttype> ] [ I<repeat> ]
1933  
1934 The option requires an argument of the given type. Supported types
1935 are:
1936  
1937 =over 4
1938  
1939 =item s
1940  
1941 String. An arbitrary sequence of characters. It is valid for the
1942 argument to start with C<-> or C<-->.
1943  
1944 =item i
1945  
1946 Integer. An optional leading plus or minus sign, followed by a
1947 sequence of digits.
1948  
1949 =item o
1950  
1951 Extended integer, Perl style. This can be either an optional leading
1952 plus or minus sign, followed by a sequence of digits, or an octal
1953 string (a zero, optionally followed by '0', '1', .. '7'), or a
1954 hexadecimal string (C<0x> followed by '0' .. '9', 'a' .. 'f', case
1955 insensitive), or a binary string (C<0b> followed by a series of '0'
1956 and '1').
1957  
1958 =item f
1959  
1960 Real number. For example C<3.14>, C<-6.23E24> and so on.
1961  
1962 =back
1963  
1964 The I<desttype> can be C<@> or C<%> to specify that the option is
1965 list or a hash valued. This is only needed when the destination for
1966 the option value is not otherwise specified. It should be omitted when
1967 not needed.
1968  
1969 The I<repeat> specifies the number of values this option takes per
1970 occurrence on the command line. It has the format C<{> [ I<min> ] [ C<,> [ I<max> ] ] C<}>.
1971  
1972 I<min> denotes the minimal number of arguments. It defaults to 1 for
1973 options with C<=> and to 0 for options with C<:>, see below. Note that
1974 I<min> overrules the C<=> / C<:> semantics.
1975  
1976 I<max> denotes the maximum number of arguments. It must be at least
1977 I<min>. If I<max> is omitted, I<but the comma is not>, there is no
1978 upper bound to the number of argument values taken.
1979  
1980 =item : I<type> [ I<desttype> ]
1981  
1982 Like C<=>, but designates the argument as optional.
1983 If omitted, an empty string will be assigned to string values options,
1984 and the value zero to numeric options.
1985  
1986 Note that if a string argument starts with C<-> or C<-->, it will be
1987 considered an option on itself.
1988  
1989 =item : I<number> [ I<desttype> ]
1990  
1991 Like C<:i>, but if the value is omitted, the I<number> will be assigned.
1992  
1993 =item : + [ I<desttype> ]
1994  
1995 Like C<:i>, but if the value is omitted, the current value for the
1996 option will be incremented.
1997  
1998 =back
1999  
2000 =head1 Advanced Possibilities
2001  
2002 =head2 Object oriented interface
2003  
2004 Getopt::Long can be used in an object oriented way as well:
2005  
2006 use Getopt::Long;
2007 $p = Getopt::Long::Parser->new;
2008 $p->configure(...configuration options...);
2009 if ($p->getoptions(...options descriptions...)) ...
2010 if ($p->getoptionsfromarray( \@array, ...options descriptions...)) ...
2011  
2012 Configuration options can be passed to the constructor:
2013  
2014 $p = new Getopt::Long::Parser
2015 config => [...configuration options...];
2016  
2017 =head2 Thread Safety
2018  
2019 Getopt::Long is thread safe when using ithreads as of Perl 5.8. It is
2020 I<not> thread safe when using the older (experimental and now
2021 obsolete) threads implementation that was added to Perl 5.005.
2022  
2023 =head2 Documentation and help texts
2024  
2025 Getopt::Long encourages the use of Pod::Usage to produce help
2026 messages. For example:
2027  
2028 use Getopt::Long;
2029 use Pod::Usage;
2030  
2031 my $man = 0;
2032 my $help = 0;
2033  
2034 GetOptions('help|?' => \$help, man => \$man) or pod2usage(2);
2035 pod2usage(1) if $help;
2036 pod2usage(-exitval => 0, -verbose => 2) if $man;
2037  
2038 __END__
2039  
2040 =head1 NAME
2041  
2042 sample - Using Getopt::Long and Pod::Usage
2043  
2044 =head1 SYNOPSIS
2045  
2046 sample [options] [file ...]
2047  
2048 Options:
2049 -help brief help message
2050 -man full documentation
2051  
2052 =head1 OPTIONS
2053  
2054 =over 8
2055  
2056 =item B<-help>
2057  
2058 Print a brief help message and exits.
2059  
2060 =item B<-man>
2061  
2062 Prints the manual page and exits.
2063  
2064 =back
2065  
2066 =head1 DESCRIPTION
2067  
2068 B<This program> will read the given input file(s) and do something
2069 useful with the contents thereof.
2070  
2071 =cut
2072  
2073 See L<Pod::Usage> for details.
2074  
2075 =head2 Parsing options from an arbitrary array
2076  
2077 By default, GetOptions parses the options that are present in the
2078 global array C<@ARGV>. A special entry C<GetOptionsFromArray> can be
2079 used to parse options from an arbitrary array.
2080  
2081 use Getopt::Long qw(GetOptionsFromArray);
2082 $ret = GetOptionsFromArray(\@myopts, ...);
2083  
2084 When used like this, options and their possible values are removed
2085 from C<@myopts>, the global C<@ARGV> is not touched at all.
2086  
2087 The following two calls behave identically:
2088  
2089 $ret = GetOptions( ... );
2090 $ret = GetOptionsFromArray(\@ARGV, ... );
2091  
2092 This also means that a first argument hash reference now becomes the
2093 second argument:
2094  
2095 $ret = GetOptions(\%opts, ... );
2096 $ret = GetOptionsFromArray(\@ARGV, \%opts, ... );
2097  
2098 =head2 Parsing options from an arbitrary string
2099  
2100 A special entry C<GetOptionsFromString> can be used to parse options
2101 from an arbitrary string.
2102  
2103 use Getopt::Long qw(GetOptionsFromString);
2104 $ret = GetOptionsFromString($string, ...);
2105  
2106 The contents of the string are split into arguments using a call to
2107 C<Text::ParseWords::shellwords>. As with C<GetOptionsFromArray>, the
2108 global C<@ARGV> is not touched.
2109  
2110 It is possible that, upon completion, not all arguments in the string
2111 have been processed. C<GetOptionsFromString> will, when called in list
2112 context, return both the return status and an array reference to any
2113 remaining arguments:
2114  
2115 ($ret, $args) = GetOptionsFromString($string, ... );
2116  
2117 If any arguments remain, and C<GetOptionsFromString> was not called in
2118 list context, a message will be given and C<GetOptionsFromString> will
2119 return failure.
2120  
2121 As with GetOptionsFromArray, a first argument hash reference now
2122 becomes the second argument.
2123  
2124 =head2 Storing options values in a hash
2125  
2126 Sometimes, for example when there are a lot of options, having a
2127 separate variable for each of them can be cumbersome. GetOptions()
2128 supports, as an alternative mechanism, storing options values in a
2129 hash.
2130  
2131 To obtain this, a reference to a hash must be passed I<as the first
2132 argument> to GetOptions(). For each option that is specified on the
2133 command line, the option value will be stored in the hash with the
2134 option name as key. Options that are not actually used on the command
2135 line will not be put in the hash, on other words,
2136 C<exists($h{option})> (or defined()) can be used to test if an option
2137 was used. The drawback is that warnings will be issued if the program
2138 runs under C<use strict> and uses C<$h{option}> without testing with
2139 exists() or defined() first.
2140  
2141 my %h = ();
2142 GetOptions (\%h, 'length=i'); # will store in $h{length}
2143  
2144 For options that take list or hash values, it is necessary to indicate
2145 this by appending an C<@> or C<%> sign after the type:
2146  
2147 GetOptions (\%h, 'colours=s@'); # will push to @{$h{colours}}
2148  
2149 To make things more complicated, the hash may contain references to
2150 the actual destinations, for example:
2151  
2152 my $len = 0;
2153 my %h = ('length' => \$len);
2154 GetOptions (\%h, 'length=i'); # will store in $len
2155  
2156 This example is fully equivalent with:
2157  
2158 my $len = 0;
2159 GetOptions ('length=i' => \$len); # will store in $len
2160  
2161 Any mixture is possible. For example, the most frequently used options
2162 could be stored in variables while all other options get stored in the
2163 hash:
2164  
2165 my $verbose = 0; # frequently referred
2166 my $debug = 0; # frequently referred
2167 my %h = ('verbose' => \$verbose, 'debug' => \$debug);
2168 GetOptions (\%h, 'verbose', 'debug', 'filter', 'size=i');
2169 if ( $verbose ) { ... }
2170 if ( exists $h{filter} ) { ... option 'filter' was specified ... }
2171  
2172 =head2 Bundling
2173  
2174 With bundling it is possible to set several single-character options
2175 at once. For example if C<a>, C<v> and C<x> are all valid options,
2176  
2177 -vax
2178  
2179 will set all three.
2180  
2181 Getopt::Long supports three styles of bundling. To enable bundling, a
2182 call to Getopt::Long::Configure is required.
2183  
2184 The simplest style of bundling can be enabled with:
2185  
2186 Getopt::Long::Configure ("bundling");
2187  
2188 Configured this way, single-character options can be bundled but long
2189 options B<must> always start with a double dash C<--> to avoid
2190 ambiguity. For example, when C<vax>, C<a>, C<v> and C<x> are all valid
2191 options,
2192  
2193 -vax
2194  
2195 will set C<a>, C<v> and C<x>, but
2196  
2197 --vax
2198  
2199 will set C<vax>.
2200  
2201 The second style of bundling lifts this restriction. It can be enabled
2202 with:
2203  
2204 Getopt::Long::Configure ("bundling_override");
2205  
2206 Now, C<-vax> will set the option C<vax>.
2207  
2208 In all of the above cases, option values may be inserted in the
2209 bundle. For example:
2210  
2211 -h24w80
2212  
2213 is equivalent to
2214  
2215 -h 24 -w 80
2216  
2217 A third style of bundling allows only values to be bundled with
2218 options. It can be enabled with:
2219  
2220 Getopt::Long::Configure ("bundling_values");
2221  
2222 Now, C<-h24> will set the option C<h> to C<24>, but option bundles
2223 like C<-vxa> and C<-h24w80> are flagged as errors.
2224  
2225 Enabling C<bundling_values> will disable the other two styles of
2226 bundling.
2227  
2228 When configured for bundling, single-character options are matched
2229 case sensitive while long options are matched case insensitive. To
2230 have the single-character options matched case insensitive as well,
2231 use:
2232  
2233 Getopt::Long::Configure ("bundling", "ignorecase_always");
2234  
2235 It goes without saying that bundling can be quite confusing.
2236  
2237 =head2 The lonesome dash
2238  
2239 Normally, a lone dash C<-> on the command line will not be considered
2240 an option. Option processing will terminate (unless "permute" is
2241 configured) and the dash will be left in C<@ARGV>.
2242  
2243 It is possible to get special treatment for a lone dash. This can be
2244 achieved by adding an option specification with an empty name, for
2245 example:
2246  
2247 GetOptions ('' => \$stdio);
2248  
2249 A lone dash on the command line will now be a legal option, and using
2250 it will set variable C<$stdio>.
2251  
2252 =head2 Argument callback
2253  
2254 A special option 'name' C<< <> >> can be used to designate a subroutine
2255 to handle non-option arguments. When GetOptions() encounters an
2256 argument that does not look like an option, it will immediately call this
2257 subroutine and passes it one parameter: the argument name. Well, actually
2258 it is an object that stringifies to the argument name.
2259  
2260 For example:
2261  
2262 my $width = 80;
2263 sub process { ... }
2264 GetOptions ('width=i' => \$width, '<>' => \&process);
2265  
2266 When applied to the following command line:
2267  
2268 arg1 --width=72 arg2 --width=60 arg3
2269  
2270 This will call
2271 C<process("arg1")> while C<$width> is C<80>,
2272 C<process("arg2")> while C<$width> is C<72>, and
2273 C<process("arg3")> while C<$width> is C<60>.
2274  
2275 This feature requires configuration option B<permute>, see section
2276 L<Configuring Getopt::Long>.
2277  
2278 =head1 Configuring Getopt::Long
2279  
2280 Getopt::Long can be configured by calling subroutine
2281 Getopt::Long::Configure(). This subroutine takes a list of quoted
2282 strings, each specifying a configuration option to be enabled, e.g.
2283 C<ignore_case>, or disabled, e.g. C<no_ignore_case>. Case does not
2284 matter. Multiple calls to Configure() are possible.
2285  
2286 Alternatively, as of version 2.24, the configuration options may be
2287 passed together with the C<use> statement:
2288  
2289 use Getopt::Long qw(:config no_ignore_case bundling);
2290  
2291 The following options are available:
2292  
2293 =over 12
2294  
2295 =item default
2296  
2297 This option causes all configuration options to be reset to their
2298 default values.
2299  
2300 =item posix_default
2301  
2302 This option causes all configuration options to be reset to their
2303 default values as if the environment variable POSIXLY_CORRECT had
2304 been set.
2305  
2306 =item auto_abbrev
2307  
2308 Allow option names to be abbreviated to uniqueness.
2309 Default is enabled unless environment variable
2310 POSIXLY_CORRECT has been set, in which case C<auto_abbrev> is disabled.
2311  
2312 =item getopt_compat
2313  
2314 Allow C<+> to start options.
2315 Default is enabled unless environment variable
2316 POSIXLY_CORRECT has been set, in which case C<getopt_compat> is disabled.
2317  
2318 =item gnu_compat
2319  
2320 C<gnu_compat> controls whether C<--opt=> is allowed, and what it should
2321 do. Without C<gnu_compat>, C<--opt=> gives an error. With C<gnu_compat>,
2322 C<--opt=> will give option C<opt> and empty value.
2323 This is the way GNU getopt_long() does it.
2324  
2325 =item gnu_getopt
2326  
2327 This is a short way of setting C<gnu_compat> C<bundling> C<permute>
2328 C<no_getopt_compat>. With C<gnu_getopt>, command line handling should be
2329 fully compatible with GNU getopt_long().
2330  
2331 =item require_order
2332  
2333 Whether command line arguments are allowed to be mixed with options.
2334 Default is disabled unless environment variable
2335 POSIXLY_CORRECT has been set, in which case C<require_order> is enabled.
2336  
2337 See also C<permute>, which is the opposite of C<require_order>.
2338  
2339 =item permute
2340  
2341 Whether command line arguments are allowed to be mixed with options.
2342 Default is enabled unless environment variable
2343 POSIXLY_CORRECT has been set, in which case C<permute> is disabled.
2344 Note that C<permute> is the opposite of C<require_order>.
2345  
2346 If C<permute> is enabled, this means that
2347  
2348 --foo arg1 --bar arg2 arg3
2349  
2350 is equivalent to
2351  
2352 --foo --bar arg1 arg2 arg3
2353  
2354 If an argument callback routine is specified, C<@ARGV> will always be
2355 empty upon successful return of GetOptions() since all options have been
2356 processed. The only exception is when C<--> is used:
2357  
2358 --foo arg1 --bar arg2 -- arg3
2359  
2360 This will call the callback routine for arg1 and arg2, and then
2361 terminate GetOptions() leaving C<"arg3"> in C<@ARGV>.
2362  
2363 If C<require_order> is enabled, options processing
2364 terminates when the first non-option is encountered.
2365  
2366 --foo arg1 --bar arg2 arg3
2367  
2368 is equivalent to
2369  
2370 --foo -- arg1 --bar arg2 arg3
2371  
2372 If C<pass_through> is also enabled, options processing will terminate
2373 at the first unrecognized option, or non-option, whichever comes
2374 first.
2375  
2376 =item bundling (default: disabled)
2377  
2378 Enabling this option will allow single-character options to be
2379 bundled. To distinguish bundles from long option names, long options
2380 I<must> be introduced with C<--> and bundles with C<->.
2381  
2382 Note that, if you have options C<a>, C<l> and C<all>, and
2383 auto_abbrev enabled, possible arguments and option settings are:
2384  
2385 using argument sets option(s)
2386 ------------------------------------------
2387 -a, --a a
2388 -l, --l l
2389 -al, -la, -ala, -all,... a, l
2390 --al, --all all
2391  
2392 The surprising part is that C<--a> sets option C<a> (due to auto
2393 completion), not C<all>.
2394  
2395 Note: disabling C<bundling> also disables C<bundling_override>.
2396  
2397 =item bundling_override (default: disabled)
2398  
2399 If C<bundling_override> is enabled, bundling is enabled as with
2400 C<bundling> but now long option names override option bundles.
2401  
2402 Note: disabling C<bundling_override> also disables C<bundling>.
2403  
2404 B<Note:> Using option bundling can easily lead to unexpected results,
2405 especially when mixing long options and bundles. Caveat emptor.
2406  
2407 =item ignore_case (default: enabled)
2408  
2409 If enabled, case is ignored when matching option names. If, however,
2410 bundling is enabled as well, single character options will be treated
2411 case-sensitive.
2412  
2413 With C<ignore_case>, option specifications for options that only
2414 differ in case, e.g., C<"foo"> and C<"Foo">, will be flagged as
2415 duplicates.
2416  
2417 Note: disabling C<ignore_case> also disables C<ignore_case_always>.
2418  
2419 =item ignore_case_always (default: disabled)
2420  
2421 When bundling is in effect, case is ignored on single-character
2422 options also.
2423  
2424 Note: disabling C<ignore_case_always> also disables C<ignore_case>.
2425  
2426 =item auto_version (default:disabled)
2427  
2428 Automatically provide support for the B<--version> option if
2429 the application did not specify a handler for this option itself.
2430  
2431 Getopt::Long will provide a standard version message that includes the
2432 program name, its version (if $main::VERSION is defined), and the
2433 versions of Getopt::Long and Perl. The message will be written to
2434 standard output and processing will terminate.
2435  
2436 C<auto_version> will be enabled if the calling program explicitly
2437 specified a version number higher than 2.32 in the C<use> or
2438 C<require> statement.
2439  
2440 =item auto_help (default:disabled)
2441  
2442 Automatically provide support for the B<--help> and B<-?> options if
2443 the application did not specify a handler for this option itself.
2444  
2445 Getopt::Long will provide a help message using module L<Pod::Usage>. The
2446 message, derived from the SYNOPSIS POD section, will be written to
2447 standard output and processing will terminate.
2448  
2449 C<auto_help> will be enabled if the calling program explicitly
2450 specified a version number higher than 2.32 in the C<use> or
2451 C<require> statement.
2452  
2453 =item pass_through (default: disabled)
2454  
2455 With C<pass_through> anything that is unknown, ambiguous or supplied with
2456 an invalid option will not be flagged as an error. Instead the unknown
2457 option(s) will be passed to the catchall C<< <> >> if present, otherwise
2458 through to C<@ARGV>. This makes it possible to write wrapper scripts that
2459 process only part of the user supplied command line arguments, and pass the
2460 remaining options to some other program.
2461  
2462 If C<require_order> is enabled, options processing will terminate at the
2463 first unrecognized option, or non-option, whichever comes first and all
2464 remaining arguments are passed to C<@ARGV> instead of the catchall
2465 C<< <> >> if present. However, if C<permute> is enabled instead, results
2466 can become confusing.
2467  
2468 Note that the options terminator (default C<-->), if present, will
2469 also be passed through in C<@ARGV>.
2470  
2471 =item prefix
2472  
2473 The string that starts options. If a constant string is not
2474 sufficient, see C<prefix_pattern>.
2475  
2476 =item prefix_pattern
2477  
2478 A Perl pattern that identifies the strings that introduce options.
2479 Default is C<--|-|\+> unless environment variable
2480 POSIXLY_CORRECT has been set, in which case it is C<--|->.
2481  
2482 =item long_prefix_pattern
2483  
2484 A Perl pattern that allows the disambiguation of long and short
2485 prefixes. Default is C<-->.
2486  
2487 Typically you only need to set this if you are using nonstandard
2488 prefixes and want some or all of them to have the same semantics as
2489 '--' does under normal circumstances.
2490  
2491 For example, setting prefix_pattern to C<--|-|\+|\/> and
2492 long_prefix_pattern to C<--|\/> would add Win32 style argument
2493 handling.
2494  
2495 =item debug (default: disabled)
2496  
2497 Enable debugging output.
2498  
2499 =back
2500  
2501 =head1 Exportable Methods
2502  
2503 =over
2504  
2505 =item VersionMessage
2506  
2507 This subroutine provides a standard version message. Its argument can be:
2508  
2509 =over 4
2510  
2511 =item *
2512  
2513 A string containing the text of a message to print I<before> printing
2514 the standard message.
2515  
2516 =item *
2517  
2518 A numeric value corresponding to the desired exit status.
2519  
2520 =item *
2521  
2522 A reference to a hash.
2523  
2524 =back
2525  
2526 If more than one argument is given then the entire argument list is
2527 assumed to be a hash. If a hash is supplied (either as a reference or
2528 as a list) it should contain one or more elements with the following
2529 keys:
2530  
2531 =over 4
2532  
2533 =item C<-message>
2534  
2535 =item C<-msg>
2536  
2537 The text of a message to print immediately prior to printing the
2538 program's usage message.
2539  
2540 =item C<-exitval>
2541  
2542 The desired exit status to pass to the B<exit()> function.
2543 This should be an integer, or else the string "NOEXIT" to
2544 indicate that control should simply be returned without
2545 terminating the invoking process.
2546  
2547 =item C<-output>
2548  
2549 A reference to a filehandle, or the pathname of a file to which the
2550 usage message should be written. The default is C<\*STDERR> unless the
2551 exit value is less than 2 (in which case the default is C<\*STDOUT>).
2552  
2553 =back
2554  
2555 You cannot tie this routine directly to an option, e.g.:
2556  
2557 GetOptions("version" => \&VersionMessage);
2558  
2559 Use this instead:
2560  
2561 GetOptions("version" => sub { VersionMessage() });
2562  
2563 =item HelpMessage
2564  
2565 This subroutine produces a standard help message, derived from the
2566 program's POD section SYNOPSIS using L<Pod::Usage>. It takes the same
2567 arguments as VersionMessage(). In particular, you cannot tie it
2568 directly to an option, e.g.:
2569  
2570 GetOptions("help" => \&HelpMessage);
2571  
2572 Use this instead:
2573  
2574 GetOptions("help" => sub { HelpMessage() });
2575  
2576 =back
2577  
2578 =head1 Return values and Errors
2579  
2580 Configuration errors and errors in the option definitions are
2581 signalled using die() and will terminate the calling program unless
2582 the call to Getopt::Long::GetOptions() was embedded in C<eval { ...
2583 }>, or die() was trapped using C<$SIG{__DIE__}>.
2584  
2585 GetOptions returns true to indicate success.
2586 It returns false when the function detected one or more errors during
2587 option parsing. These errors are signalled using warn() and can be
2588 trapped with C<$SIG{__WARN__}>.
2589  
2590 =head1 Legacy
2591  
2592 The earliest development of C<newgetopt.pl> started in 1990, with Perl
2593 version 4. As a result, its development, and the development of
2594 Getopt::Long, has gone through several stages. Since backward
2595 compatibility has always been extremely important, the current version
2596 of Getopt::Long still supports a lot of constructs that nowadays are
2597 no longer necessary or otherwise unwanted. This section describes
2598 briefly some of these 'features'.
2599  
2600 =head2 Default destinations
2601  
2602 When no destination is specified for an option, GetOptions will store
2603 the resultant value in a global variable named C<opt_>I<XXX>, where
2604 I<XXX> is the primary name of this option. When a program executes
2605 under C<use strict> (recommended), these variables must be
2606 pre-declared with our() or C<use vars>.
2607  
2608 our $opt_length = 0;
2609 GetOptions ('length=i'); # will store in $opt_length
2610  
2611 To yield a usable Perl variable, characters that are not part of the
2612 syntax for variables are translated to underscores. For example,
2613 C<--fpp-struct-return> will set the variable
2614 C<$opt_fpp_struct_return>. Note that this variable resides in the
2615 namespace of the calling program, not necessarily C<main>. For
2616 example:
2617  
2618 GetOptions ("size=i", "sizes=i@");
2619  
2620 with command line "-size 10 -sizes 24 -sizes 48" will perform the
2621 equivalent of the assignments
2622  
2623 $opt_size = 10;
2624 @opt_sizes = (24, 48);
2625  
2626 =head2 Alternative option starters
2627  
2628 A string of alternative option starter characters may be passed as the
2629 first argument (or the first argument after a leading hash reference
2630 argument).
2631  
2632 my $len = 0;
2633 GetOptions ('/', 'length=i' => $len);
2634  
2635 Now the command line may look like:
2636  
2637 /length 24 -- arg
2638  
2639 Note that to terminate options processing still requires a double dash
2640 C<-->.
2641  
2642 GetOptions() will not interpret a leading C<< "<>" >> as option starters
2643 if the next argument is a reference. To force C<< "<" >> and C<< ">" >> as
2644 option starters, use C<< "><" >>. Confusing? Well, B<using a starter
2645 argument is strongly deprecated> anyway.
2646  
2647 =head2 Configuration variables
2648  
2649 Previous versions of Getopt::Long used variables for the purpose of
2650 configuring. Although manipulating these variables still work, it is
2651 strongly encouraged to use the C<Configure> routine that was introduced
2652 in version 2.17. Besides, it is much easier.
2653  
2654 =head1 Tips and Techniques
2655  
2656 =head2 Pushing multiple values in a hash option
2657  
2658 Sometimes you want to combine the best of hashes and arrays. For
2659 example, the command line:
2660  
2661 --list add=first --list add=second --list add=third
2662  
2663 where each successive 'list add' option will push the value of add
2664 into array ref $list->{'add'}. The result would be like
2665  
2666 $list->{add} = [qw(first second third)];
2667  
2668 This can be accomplished with a destination routine:
2669  
2670 GetOptions('list=s%' =>
2671 sub { push(@{$list{$_[1]}}, $_[2]) });
2672  
2673 =head1 Troubleshooting
2674  
2675 =head2 GetOptions does not return a false result when an option is not supplied
2676  
2677 That's why they're called 'options'.
2678  
2679 =head2 GetOptions does not split the command line correctly
2680  
2681 The command line is not split by GetOptions, but by the command line
2682 interpreter (CLI). On Unix, this is the shell. On Windows, it is
2683 COMMAND.COM or CMD.EXE. Other operating systems have other CLIs.
2684  
2685 It is important to know that these CLIs may behave different when the
2686 command line contains special characters, in particular quotes or
2687 backslashes. For example, with Unix shells you can use single quotes
2688 (C<'>) and double quotes (C<">) to group words together. The following
2689 alternatives are equivalent on Unix:
2690  
2691 "two words"
2692 'two words'
2693 two\ words
2694  
2695 In case of doubt, insert the following statement in front of your Perl
2696 program:
2697  
2698 print STDERR (join("|",@ARGV),"\n");
2699  
2700 to verify how your CLI passes the arguments to the program.
2701  
2702 =head2 Undefined subroutine &main::GetOptions called
2703  
2704 Are you running Windows, and did you write
2705  
2706 use GetOpt::Long;
2707  
2708 (note the capital 'O')?
2709  
2710 =head2 How do I put a "-?" option into a Getopt::Long?
2711  
2712 You can only obtain this using an alias, and Getopt::Long of at least
2713 version 2.13.
2714  
2715 use Getopt::Long;
2716 GetOptions ("help|?"); # -help and -? will both set $opt_help
2717  
2718 Other characters that can't appear in Perl identifiers are also supported
2719 as aliases with Getopt::Long of at least version 2.39.
2720  
2721 As of version 2.32 Getopt::Long provides auto-help, a quick and easy way
2722 to add the options --help and -? to your program, and handle them.
2723  
2724 See C<auto_help> in section L<Configuring Getopt::Long>.
2725  
2726 =head1 AUTHOR
2727  
2728 Johan Vromans <jvromans@squirrel.nl>
2729  
2730 =head1 COPYRIGHT AND DISCLAIMER
2731  
2732 This program is Copyright 1990,2015 by Johan Vromans.
2733 This program is free software; you can redistribute it and/or
2734 modify it under the terms of the Perl Artistic License or the
2735 GNU General Public License as published by the Free Software
2736 Foundation; either version 2 of the License, or (at your option) any
2737 later version.
2738  
2739 This program is distributed in the hope that it will be useful,
2740 but WITHOUT ANY WARRANTY; without even the implied warranty of
2741 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2742 GNU General Public License for more details.
2743  
2744 If you do not have a copy of the GNU General Public License write to
2745 the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
2746 MA 02139, USA.
2747  
2748 =cut
2749