File Coverage

blib/lib/Getopt/Long.pm
Criterion Covered Total %
statement 382 701 54.4
branch 208 622 33.4
condition 103 308 33.4
subroutine 38 48 79.1
pod 0 8 0.0
total 731 1687 43.3


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