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