File Coverage

blib/lib/Getopt/Long.pm
Criterion Covered Total %
statement 348 666 52.2
branch 207 618 33.5
condition 101 299 33.7
subroutine 32 42 76.1
pod 3 15 20.0
total 691 1640 42.1


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