Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1890 lines
57 KiB

  1. # GetOpt::Long.pm -- Universal options parsing
  2. package Getopt::Long;
  3. # RCS Status : $Id: GetoptLong.pl,v 2.26 2001-01-31 10:20:29+01 jv Exp $
  4. # Author : Johan Vromans
  5. # Created On : Tue Sep 11 15:00:12 1990
  6. # Last Modified By: Johan Vromans
  7. # Last Modified On: Sat Jan 6 17:12:27 2001
  8. # Update Count : 748
  9. # Status : Released
  10. ################ Copyright ################
  11. # This program is Copyright 1990,2001 by Johan Vromans.
  12. # This program is free software; you can redistribute it and/or
  13. # modify it under the terms of the Perl Artistic License or the
  14. # GNU General Public License as published by the Free Software
  15. # Foundation; either version 2 of the License, or (at your option) any
  16. # later version.
  17. #
  18. # This program is distributed in the hope that it will be useful,
  19. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. # GNU General Public License for more details.
  22. #
  23. # If you do not have a copy of the GNU General Public License write to
  24. # the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
  25. # MA 02139, USA.
  26. ################ Module Preamble ################
  27. use 5.004;
  28. use strict;
  29. use vars qw($VERSION $VERSION_STRING);
  30. $VERSION = 2.25;
  31. $VERSION_STRING = "2.25";
  32. use Exporter;
  33. use AutoLoader qw(AUTOLOAD);
  34. use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
  35. @ISA = qw(Exporter);
  36. %EXPORT_TAGS = qw();
  37. BEGIN {
  38. # Init immediately so their contents can be used in the 'use vars' below.
  39. @EXPORT = qw(&GetOptions $REQUIRE_ORDER $PERMUTE $RETURN_IN_ORDER);
  40. @EXPORT_OK = qw();
  41. }
  42. # User visible variables.
  43. use vars @EXPORT, @EXPORT_OK;
  44. use vars qw($error $debug $major_version $minor_version);
  45. # Deprecated visible variables.
  46. use vars qw($autoabbrev $getopt_compat $ignorecase $bundling $order
  47. $passthrough);
  48. # Official invisible variables.
  49. use vars qw($genprefix $caller $gnu_compat);
  50. # Public subroutines.
  51. sub Configure (@);
  52. sub config (@); # deprecated name
  53. sub GetOptions;
  54. # Private subroutines.
  55. sub ConfigDefaults ();
  56. sub FindOption ($$$$$$$);
  57. sub Croak (@); # demand loading the real Croak
  58. ################ Local Variables ################
  59. ################ Resident subroutines ################
  60. sub ConfigDefaults () {
  61. # Handle POSIX compliancy.
  62. if ( defined $ENV{"POSIXLY_CORRECT"} ) {
  63. $genprefix = "(--|-)";
  64. $autoabbrev = 0; # no automatic abbrev of options
  65. $bundling = 0; # no bundling of single letter switches
  66. $getopt_compat = 0; # disallow '+' to start options
  67. $order = $REQUIRE_ORDER;
  68. }
  69. else {
  70. $genprefix = "(--|-|\\+)";
  71. $autoabbrev = 1; # automatic abbrev of options
  72. $bundling = 0; # bundling off by default
  73. $getopt_compat = 1; # allow '+' to start options
  74. $order = $PERMUTE;
  75. }
  76. # Other configurable settings.
  77. $debug = 0; # for debugging
  78. $error = 0; # error tally
  79. $ignorecase = 1; # ignore case when matching options
  80. $passthrough = 0; # leave unrecognized options alone
  81. $gnu_compat = 0; # require --opt=val if value is optional
  82. }
  83. # Override import.
  84. sub import {
  85. my $pkg = shift; # package
  86. my @syms = (); # symbols to import
  87. my @config = (); # configuration
  88. my $dest = \@syms; # symbols first
  89. for ( @_ ) {
  90. if ( $_ eq ':config' ) {
  91. $dest = \@config; # config next
  92. next;
  93. }
  94. push (@$dest, $_); # push
  95. }
  96. # Hide one level and call super.
  97. local $Exporter::ExportLevel = 1;
  98. $pkg->SUPER::import(@syms);
  99. # And configure.
  100. Configure (@config) if @config;
  101. }
  102. ################ Initialization ################
  103. # Values for $order. See GNU getopt.c for details.
  104. ($REQUIRE_ORDER, $PERMUTE, $RETURN_IN_ORDER) = (0..2);
  105. # Version major/minor numbers.
  106. ($major_version, $minor_version) = $VERSION =~ /^(\d+)\.(\d+)/;
  107. ConfigDefaults();
  108. ################ OO Interface ################
  109. package Getopt::Long::Parser;
  110. # NOTE: The object oriented routines use $error for thread locking.
  111. my $_lock = sub {
  112. lock ($Getopt::Long::error) if $] >= 5.005
  113. };
  114. # Store a copy of the default configuration. Since ConfigDefaults has
  115. # just been called, what we get from Configure is the default.
  116. my $default_config = do {
  117. &$_lock;
  118. Getopt::Long::Configure ()
  119. };
  120. sub new {
  121. my $that = shift;
  122. my $class = ref($that) || $that;
  123. my %atts = @_;
  124. # Register the callers package.
  125. my $self = { caller_pkg => (caller)[0] };
  126. bless ($self, $class);
  127. # Process config attributes.
  128. if ( defined $atts{config} ) {
  129. &$_lock;
  130. my $save = Getopt::Long::Configure ($default_config, @{$atts{config}});
  131. $self->{settings} = Getopt::Long::Configure ($save);
  132. delete ($atts{config});
  133. }
  134. # Else use default config.
  135. else {
  136. $self->{settings} = $default_config;
  137. }
  138. if ( %atts ) { # Oops
  139. Getopt::Long::Croak(__PACKAGE__.": unhandled attributes: ".
  140. join(" ", sort(keys(%atts))));
  141. }
  142. $self;
  143. }
  144. sub configure {
  145. my ($self) = shift;
  146. &$_lock;
  147. # Restore settings, merge new settings in.
  148. my $save = Getopt::Long::Configure ($self->{settings}, @_);
  149. # Restore orig config and save the new config.
  150. $self->{settings} = Configure ($save);
  151. }
  152. sub getoptions {
  153. my ($self) = shift;
  154. &$_lock;
  155. # Restore config settings.
  156. my $save = Getopt::Long::Configure ($self->{settings});
  157. # Call main routine.
  158. my $ret = 0;
  159. $Getopt::Long::caller = $self->{caller_pkg};
  160. eval { $ret = Getopt::Long::GetOptions (@_); };
  161. # Restore saved settings.
  162. Getopt::Long::Configure ($save);
  163. # Handle errors and return value.
  164. die ($@) if $@;
  165. return $ret;
  166. }
  167. package Getopt::Long;
  168. ################ Package return ################
  169. 1;
  170. __END__
  171. ################ AutoLoading subroutines ################
  172. # RCS Status : $Id: GetoptLongAl.pl,v 2.30 2001-01-31 10:21:11+01 jv Exp $
  173. # Author : Johan Vromans
  174. # Created On : Fri Mar 27 11:50:30 1998
  175. # Last Modified By: Johan Vromans
  176. # Last Modified On: Tue Dec 26 18:01:16 2000
  177. # Update Count : 98
  178. # Status : Released
  179. sub GetOptions {
  180. my @optionlist = @_; # local copy of the option descriptions
  181. my $argend = '--'; # option list terminator
  182. my %opctl = (); # table of arg.specs (long and abbrevs)
  183. my %bopctl = (); # table of arg.specs (bundles)
  184. my $pkg = $caller || (caller)[0]; # current context
  185. # Needed if linkage is omitted.
  186. my %aliases= (); # alias table
  187. my @ret = (); # accum for non-options
  188. my %linkage; # linkage
  189. my $userlinkage; # user supplied HASH
  190. my $opt; # current option
  191. my $genprefix = $genprefix; # so we can call the same module many times
  192. my @opctl; # the possible long option names
  193. $error = '';
  194. print STDERR ("GetOpt::Long $Getopt::Long::VERSION ",
  195. "called from package \"$pkg\".",
  196. "\n ",
  197. 'GetOptionsAl $Revision: 2.30 $ ',
  198. "\n ",
  199. "ARGV: (@ARGV)",
  200. "\n ",
  201. "autoabbrev=$autoabbrev,".
  202. "bundling=$bundling,",
  203. "getopt_compat=$getopt_compat,",
  204. "gnu_compat=$gnu_compat,",
  205. "order=$order,",
  206. "\n ",
  207. "ignorecase=$ignorecase,",
  208. "passthrough=$passthrough,",
  209. "genprefix=\"$genprefix\".",
  210. "\n")
  211. if $debug;
  212. # Check for ref HASH as first argument.
  213. # First argument may be an object. It's OK to use this as long
  214. # as it is really a hash underneath.
  215. $userlinkage = undef;
  216. if ( ref($optionlist[0]) and
  217. "$optionlist[0]" =~ /^(?:.*\=)?HASH\([^\(]*\)$/ ) {
  218. $userlinkage = shift (@optionlist);
  219. print STDERR ("=> user linkage: $userlinkage\n") if $debug;
  220. }
  221. # See if the first element of the optionlist contains option
  222. # starter characters.
  223. # Be careful not to interpret '<>' as option starters.
  224. if ( $optionlist[0] =~ /^\W+$/
  225. && !($optionlist[0] eq '<>'
  226. && @optionlist > 0
  227. && ref($optionlist[1])) ) {
  228. $genprefix = shift (@optionlist);
  229. # Turn into regexp. Needs to be parenthesized!
  230. $genprefix =~ s/(\W)/\\$1/g;
  231. $genprefix = "([" . $genprefix . "])";
  232. }
  233. # Verify correctness of optionlist.
  234. %opctl = ();
  235. %bopctl = ();
  236. while ( @optionlist > 0 ) {
  237. my $opt = shift (@optionlist);
  238. # Strip leading prefix so people can specify "--foo=i" if they like.
  239. $opt = $+ if $opt =~ /^$genprefix+(.*)$/s;
  240. if ( $opt eq '<>' ) {
  241. if ( (defined $userlinkage)
  242. && !(@optionlist > 0 && ref($optionlist[0]))
  243. && (exists $userlinkage->{$opt})
  244. && ref($userlinkage->{$opt}) ) {
  245. unshift (@optionlist, $userlinkage->{$opt});
  246. }
  247. unless ( @optionlist > 0
  248. && ref($optionlist[0]) && ref($optionlist[0]) eq 'CODE' ) {
  249. $error .= "Option spec <> requires a reference to a subroutine\n";
  250. next;
  251. }
  252. $linkage{'<>'} = shift (@optionlist);
  253. next;
  254. }
  255. # Match option spec. Allow '?' as an alias only.
  256. if ( $opt !~ /^((\w+[-\w]*)(\|(\?|\w[-\w]*)?)*)?([!~+]|[=:][infse][@%]?)?$/ ) {
  257. $error .= "Error in option spec: \"$opt\"\n";
  258. next;
  259. }
  260. my ($o, $c, $a) = ($1, $5);
  261. $c = '' unless defined $c;
  262. # $linko keeps track of the primary name the user specified.
  263. # This name will be used for the internal or external linkage.
  264. # In other words, if the user specifies "FoO|BaR", it will
  265. # match any case combinations of 'foo' and 'bar', but if a global
  266. # variable needs to be set, it will be $opt_FoO in the exact case
  267. # as specified.
  268. my $linko;
  269. if ( ! defined $o ) {
  270. # empty -> '-' option
  271. $linko = $o = '';
  272. $opctl{''} = $c;
  273. $bopctl{''} = $c if $bundling;
  274. }
  275. else {
  276. # Handle alias names
  277. my @o = split (/\|/, $o);
  278. $linko = $o = $o[0];
  279. # Force an alias if the option name is not locase.
  280. $a = $o unless $o eq lc($o);
  281. $o = lc ($o)
  282. if $ignorecase > 1
  283. || ($ignorecase
  284. && ($bundling ? length($o) > 1 : 1));
  285. foreach ( @o ) {
  286. if ( $bundling && length($_) == 1 ) {
  287. $_ = lc ($_) if $ignorecase > 1;
  288. if ( $c eq '!' ) {
  289. $opctl{"no$_"} = $c;
  290. warn ("Ignoring '!' modifier for short option $_\n");
  291. $opctl{$_} = $bopctl{$_} = '';
  292. }
  293. else {
  294. $opctl{$_} = $bopctl{$_} = $c;
  295. }
  296. }
  297. else {
  298. $_ = lc ($_) if $ignorecase;
  299. if ( $c eq '!' ) {
  300. $opctl{"no$_"} = $c;
  301. $opctl{$_} = ''
  302. }
  303. else {
  304. $opctl{$_} = $c;
  305. }
  306. }
  307. if ( defined $a ) {
  308. # Note alias.
  309. $aliases{$_} = $a;
  310. }
  311. else {
  312. # Set primary name.
  313. $a = $_;
  314. }
  315. }
  316. }
  317. # If no linkage is supplied in the @optionlist, copy it from
  318. # the userlinkage if available.
  319. if ( defined $userlinkage ) {
  320. unless ( @optionlist > 0 && ref($optionlist[0]) ) {
  321. if ( exists $userlinkage->{$linko} &&
  322. ref($userlinkage->{$linko}) ) {
  323. print STDERR ("=> found userlinkage for \"$linko\": ",
  324. "$userlinkage->{$linko}\n")
  325. if $debug;
  326. unshift (@optionlist, $userlinkage->{$linko});
  327. }
  328. else {
  329. # Do nothing. Being undefined will be handled later.
  330. next;
  331. }
  332. }
  333. }
  334. # Copy the linkage. If omitted, link to global variable.
  335. if ( @optionlist > 0 && ref($optionlist[0]) ) {
  336. print STDERR ("=> link \"$linko\" to $optionlist[0]\n")
  337. if $debug;
  338. if ( ref($optionlist[0]) =~ /^(SCALAR|CODE)$/ ) {
  339. $linkage{$linko} = shift (@optionlist);
  340. }
  341. elsif ( ref($optionlist[0]) =~ /^(ARRAY)$/ ) {
  342. $linkage{$linko} = shift (@optionlist);
  343. $opctl{$o} .= '@'
  344. if $opctl{$o} ne '' and $opctl{$o} !~ /\@$/;
  345. $bopctl{$o} .= '@'
  346. if $bundling and defined $bopctl{$o} and
  347. $bopctl{$o} ne '' and $bopctl{$o} !~ /\@$/;
  348. }
  349. elsif ( ref($optionlist[0]) =~ /^(HASH)$/ ) {
  350. $linkage{$linko} = shift (@optionlist);
  351. $opctl{$o} .= '%'
  352. if $opctl{$o} ne '' and $opctl{$o} !~ /\%$/;
  353. $bopctl{$o} .= '%'
  354. if $bundling and defined $bopctl{$o} and
  355. $bopctl{$o} ne '' and $bopctl{$o} !~ /\%$/;
  356. }
  357. else {
  358. $error .= "Invalid option linkage for \"$opt\"\n";
  359. }
  360. }
  361. else {
  362. # Link to global $opt_XXX variable.
  363. # Make sure a valid perl identifier results.
  364. my $ov = $linko;
  365. $ov =~ s/\W/_/g;
  366. if ( $c =~ /@/ ) {
  367. print STDERR ("=> link \"$linko\" to \@$pkg","::opt_$ov\n")
  368. if $debug;
  369. eval ("\$linkage{\$linko} = \\\@".$pkg."::opt_$ov;");
  370. }
  371. elsif ( $c =~ /%/ ) {
  372. print STDERR ("=> link \"$linko\" to \%$pkg","::opt_$ov\n")
  373. if $debug;
  374. eval ("\$linkage{\$linko} = \\\%".$pkg."::opt_$ov;");
  375. }
  376. else {
  377. print STDERR ("=> link \"$linko\" to \$$pkg","::opt_$ov\n")
  378. if $debug;
  379. eval ("\$linkage{\$linko} = \\\$".$pkg."::opt_$ov;");
  380. }
  381. }
  382. }
  383. # Bail out if errors found.
  384. die ($error) if $error;
  385. $error = 0;
  386. # Sort the possible long option names.
  387. @opctl = sort(keys (%opctl)) if $autoabbrev;
  388. # Show the options tables if debugging.
  389. if ( $debug ) {
  390. my ($arrow, $k, $v);
  391. $arrow = "=> ";
  392. while ( ($k,$v) = each(%opctl) ) {
  393. print STDERR ($arrow, "\$opctl{\"$k\"} = \"$v\"\n");
  394. $arrow = " ";
  395. }
  396. $arrow = "=> ";
  397. while ( ($k,$v) = each(%bopctl) ) {
  398. print STDERR ($arrow, "\$bopctl{\"$k\"} = \"$v\"\n");
  399. $arrow = " ";
  400. }
  401. }
  402. # Process argument list
  403. my $goon = 1;
  404. while ( $goon && @ARGV > 0 ) {
  405. #### Get next argument ####
  406. $opt = shift (@ARGV);
  407. print STDERR ("=> option \"", $opt, "\"\n") if $debug;
  408. #### Determine what we have ####
  409. # Double dash is option list terminator.
  410. if ( $opt eq $argend ) {
  411. # Finish. Push back accumulated arguments and return.
  412. unshift (@ARGV, @ret)
  413. if $order == $PERMUTE;
  414. return ($error == 0);
  415. }
  416. my $tryopt = $opt;
  417. my $found; # success status
  418. my $dsttype; # destination type ('@' or '%')
  419. my $incr; # destination increment
  420. my $key; # key (if hash type)
  421. my $arg; # option argument
  422. ($found, $opt, $arg, $dsttype, $incr, $key) =
  423. FindOption ($genprefix, $argend, $opt,
  424. \%opctl, \%bopctl, \@opctl, \%aliases);
  425. if ( $found ) {
  426. # FindOption undefines $opt in case of errors.
  427. next unless defined $opt;
  428. if ( defined $arg ) {
  429. if ( defined $aliases{$opt} ) {
  430. print STDERR ("=> alias \"$opt\" -> \"$aliases{$opt}\"\n")
  431. if $debug;
  432. $opt = $aliases{$opt};
  433. }
  434. if ( defined $linkage{$opt} ) {
  435. print STDERR ("=> ref(\$L{$opt}) -> ",
  436. ref($linkage{$opt}), "\n") if $debug;
  437. if ( ref($linkage{$opt}) eq 'SCALAR' ) {
  438. if ( $incr ) {
  439. print STDERR ("=> \$\$L{$opt} += \"$arg\"\n")
  440. if $debug;
  441. if ( defined ${$linkage{$opt}} ) {
  442. ${$linkage{$opt}} += $arg;
  443. }
  444. else {
  445. ${$linkage{$opt}} = $arg;
  446. }
  447. }
  448. else {
  449. print STDERR ("=> \$\$L{$opt} = \"$arg\"\n")
  450. if $debug;
  451. ${$linkage{$opt}} = $arg;
  452. }
  453. }
  454. elsif ( ref($linkage{$opt}) eq 'ARRAY' ) {
  455. print STDERR ("=> push(\@{\$L{$opt}, \"$arg\")\n")
  456. if $debug;
  457. push (@{$linkage{$opt}}, $arg);
  458. }
  459. elsif ( ref($linkage{$opt}) eq 'HASH' ) {
  460. print STDERR ("=> \$\$L{$opt}->{$key} = \"$arg\"\n")
  461. if $debug;
  462. $linkage{$opt}->{$key} = $arg;
  463. }
  464. elsif ( ref($linkage{$opt}) eq 'CODE' ) {
  465. print STDERR ("=> &L{$opt}(\"$opt\", \"$arg\")\n")
  466. if $debug;
  467. local ($@);
  468. eval {
  469. &{$linkage{$opt}}($opt, $arg);
  470. };
  471. print STDERR ("=> die($@)\n") if $debug && $@ ne '';
  472. if ( $@ =~ /^!/ ) {
  473. if ( $@ =~ /^!FINISH\b/ ) {
  474. $goon = 0;
  475. }
  476. }
  477. elsif ( $@ ne '' ) {
  478. warn ($@);
  479. $error++;
  480. }
  481. }
  482. else {
  483. print STDERR ("Invalid REF type \"", ref($linkage{$opt}),
  484. "\" in linkage\n");
  485. Croak ("Getopt::Long -- internal error!\n");
  486. }
  487. }
  488. # No entry in linkage means entry in userlinkage.
  489. elsif ( $dsttype eq '@' ) {
  490. if ( defined $userlinkage->{$opt} ) {
  491. print STDERR ("=> push(\@{\$L{$opt}}, \"$arg\")\n")
  492. if $debug;
  493. push (@{$userlinkage->{$opt}}, $arg);
  494. }
  495. else {
  496. print STDERR ("=>\$L{$opt} = [\"$arg\"]\n")
  497. if $debug;
  498. $userlinkage->{$opt} = [$arg];
  499. }
  500. }
  501. elsif ( $dsttype eq '%' ) {
  502. if ( defined $userlinkage->{$opt} ) {
  503. print STDERR ("=> \$L{$opt}->{$key} = \"$arg\"\n")
  504. if $debug;
  505. $userlinkage->{$opt}->{$key} = $arg;
  506. }
  507. else {
  508. print STDERR ("=>\$L{$opt} = {$key => \"$arg\"}\n")
  509. if $debug;
  510. $userlinkage->{$opt} = {$key => $arg};
  511. }
  512. }
  513. else {
  514. if ( $incr ) {
  515. print STDERR ("=> \$L{$opt} += \"$arg\"\n")
  516. if $debug;
  517. if ( defined $userlinkage->{$opt} ) {
  518. $userlinkage->{$opt} += $arg;
  519. }
  520. else {
  521. $userlinkage->{$opt} = $arg;
  522. }
  523. }
  524. else {
  525. print STDERR ("=>\$L{$opt} = \"$arg\"\n") if $debug;
  526. $userlinkage->{$opt} = $arg;
  527. }
  528. }
  529. }
  530. }
  531. # Not an option. Save it if we $PERMUTE and don't have a <>.
  532. elsif ( $order == $PERMUTE ) {
  533. # Try non-options call-back.
  534. my $cb;
  535. if ( (defined ($cb = $linkage{'<>'})) ) {
  536. local ($@);
  537. eval {
  538. &$cb ($tryopt);
  539. };
  540. print STDERR ("=> die($@)\n") if $debug && $@ ne '';
  541. if ( $@ =~ /^!/ ) {
  542. if ( $@ =~ /^!FINISH\b/ ) {
  543. $goon = 0;
  544. }
  545. }
  546. elsif ( $@ ne '' ) {
  547. warn ($@);
  548. $error++;
  549. }
  550. }
  551. else {
  552. print STDERR ("=> saving \"$tryopt\" ",
  553. "(not an option, may permute)\n") if $debug;
  554. push (@ret, $tryopt);
  555. }
  556. next;
  557. }
  558. # ...otherwise, terminate.
  559. else {
  560. # Push this one back and exit.
  561. unshift (@ARGV, $tryopt);
  562. return ($error == 0);
  563. }
  564. }
  565. # Finish.
  566. if ( $order == $PERMUTE ) {
  567. # Push back accumulated arguments
  568. print STDERR ("=> restoring \"", join('" "', @ret), "\"\n")
  569. if $debug && @ret > 0;
  570. unshift (@ARGV, @ret) if @ret > 0;
  571. }
  572. return ($error == 0);
  573. }
  574. # Option lookup.
  575. sub FindOption ($$$$$$$) {
  576. # returns (1, $opt, $arg, $dsttype, $incr, $key) if okay,
  577. # returns (0) otherwise.
  578. my ($prefix, $argend, $opt, $opctl, $bopctl, $names, $aliases) = @_;
  579. my $key; # hash key for a hash option
  580. my $arg;
  581. print STDERR ("=> find \"$opt\", prefix=\"$prefix\"\n") if $debug;
  582. return 0 unless $opt =~ /^$prefix(.*)$/s;
  583. return 0 if $opt eq "-" && !defined $opctl->{""};
  584. $opt = $+;
  585. my ($starter) = $1;
  586. print STDERR ("=> split \"$starter\"+\"$opt\"\n") if $debug;
  587. my $optarg = undef; # value supplied with --opt=value
  588. my $rest = undef; # remainder from unbundling
  589. # If it is a long option, it may include the value.
  590. if (($starter eq "--" || ($getopt_compat && !$bundling))
  591. && $opt =~ /^([^=]+)=(.*)$/s ) {
  592. $opt = $1;
  593. $optarg = $2;
  594. print STDERR ("=> option \"", $opt,
  595. "\", optarg = \"$optarg\"\n") if $debug;
  596. }
  597. #### Look it up ###
  598. my $tryopt = $opt; # option to try
  599. my $optbl = $opctl; # table to look it up (long names)
  600. my $type;
  601. my $dsttype = '';
  602. my $incr = 0;
  603. if ( $bundling && $starter eq '-' ) {
  604. # Unbundle single letter option.
  605. $rest = length ($tryopt) > 0 ? substr ($tryopt, 1) : "";
  606. $tryopt = substr ($tryopt, 0, 1);
  607. $tryopt = lc ($tryopt) if $ignorecase > 1;
  608. print STDERR ("=> $starter$tryopt unbundled from ",
  609. "$starter$tryopt$rest\n") if $debug;
  610. $rest = undef unless $rest ne '';
  611. $optbl = $bopctl; # look it up in the short names table
  612. # If bundling == 2, long options can override bundles.
  613. if ( $bundling == 2 and
  614. defined ($rest) and
  615. defined ($type = $opctl->{$tryopt.$rest}) ) {
  616. print STDERR ("=> $starter$tryopt rebundled to ",
  617. "$starter$tryopt$rest\n") if $debug;
  618. $tryopt .= $rest;
  619. undef $rest;
  620. }
  621. }
  622. # Try auto-abbreviation.
  623. elsif ( $autoabbrev ) {
  624. # Downcase if allowed.
  625. $tryopt = $opt = lc ($opt) if $ignorecase;
  626. # Turn option name into pattern.
  627. my $pat = quotemeta ($opt);
  628. # Look up in option names.
  629. my @hits = grep (/^$pat/, @{$names});
  630. print STDERR ("=> ", scalar(@hits), " hits (@hits) with \"$pat\" ",
  631. "out of ", scalar(@{$names}), "\n") if $debug;
  632. # Check for ambiguous results.
  633. unless ( (@hits <= 1) || (grep ($_ eq $opt, @hits) == 1) ) {
  634. # See if all matches are for the same option.
  635. my %hit;
  636. foreach ( @hits ) {
  637. $_ = $aliases->{$_} if defined $aliases->{$_};
  638. $hit{$_} = 1;
  639. }
  640. # Now see if it really is ambiguous.
  641. unless ( keys(%hit) == 1 ) {
  642. return (0) if $passthrough;
  643. warn ("Option ", $opt, " is ambiguous (",
  644. join(", ", @hits), ")\n");
  645. $error++;
  646. undef $opt;
  647. return (1, $opt,$arg,$dsttype,$incr,$key);
  648. }
  649. @hits = keys(%hit);
  650. }
  651. # Complete the option name, if appropriate.
  652. if ( @hits == 1 && $hits[0] ne $opt ) {
  653. $tryopt = $hits[0];
  654. $tryopt = lc ($tryopt) if $ignorecase;
  655. print STDERR ("=> option \"$opt\" -> \"$tryopt\"\n")
  656. if $debug;
  657. }
  658. }
  659. # Map to all lowercase if ignoring case.
  660. elsif ( $ignorecase ) {
  661. $tryopt = lc ($opt);
  662. }
  663. # Check validity by fetching the info.
  664. $type = $optbl->{$tryopt} unless defined $type;
  665. unless ( defined $type ) {
  666. return (0) if $passthrough;
  667. warn ("Unknown option: ", $opt, "\n");
  668. $error++;
  669. return (1, $opt,$arg,$dsttype,$incr,$key);
  670. }
  671. # Apparently valid.
  672. $opt = $tryopt;
  673. print STDERR ("=> found \"$type\" for \"", $opt, "\"\n") if $debug;
  674. #### Determine argument status ####
  675. # If it is an option w/o argument, we're almost finished with it.
  676. if ( $type eq '' || $type eq '!' || $type eq '+' ) {
  677. if ( defined $optarg ) {
  678. return (0) if $passthrough;
  679. warn ("Option ", $opt, " does not take an argument\n");
  680. $error++;
  681. undef $opt;
  682. }
  683. elsif ( $type eq '' || $type eq '+' ) {
  684. $arg = 1; # supply explicit value
  685. $incr = $type eq '+';
  686. }
  687. else {
  688. substr ($opt, 0, 2) = ''; # strip NO prefix
  689. $arg = 0; # supply explicit value
  690. }
  691. unshift (@ARGV, $starter.$rest) if defined $rest;
  692. return (1, $opt,$arg,$dsttype,$incr,$key);
  693. }
  694. # Get mandatory status and type info.
  695. my $mand;
  696. ($mand, $type, $dsttype, $key) = $type =~ /^(.)(.)([@%]?)$/;
  697. # Check if there is an option argument available.
  698. if ( $gnu_compat ) {
  699. return (1, $opt, $optarg, $dsttype, $incr, $key)
  700. if defined $optarg;
  701. return (1, $opt, $type eq "s" ? '' : 0, $dsttype, $incr, $key)
  702. if $mand eq ':';
  703. }
  704. # Check if there is an option argument available.
  705. if ( defined $optarg
  706. ? ($optarg eq '')
  707. : !(defined $rest || @ARGV > 0) ) {
  708. # Complain if this option needs an argument.
  709. if ( $mand eq "=" ) {
  710. return (0) if $passthrough;
  711. warn ("Option ", $opt, " requires an argument\n");
  712. $error++;
  713. undef $opt;
  714. }
  715. return (1, $opt, $type eq "s" ? '' : 0, $dsttype, $incr, $key);
  716. }
  717. # Get (possibly optional) argument.
  718. $arg = (defined $rest ? $rest
  719. : (defined $optarg ? $optarg : shift (@ARGV)));
  720. # Get key if this is a "name=value" pair for a hash option.
  721. $key = undef;
  722. if ($dsttype eq '%' && defined $arg) {
  723. ($key, $arg) = ($arg =~ /^([^=]*)=(.*)$/s) ? ($1, $2) : ($arg, 1);
  724. }
  725. #### Check if the argument is valid for this option ####
  726. if ( $type eq "s" ) { # string
  727. # A mandatory string takes anything.
  728. return (1, $opt,$arg,$dsttype,$incr,$key) if $mand eq "=";
  729. # An optional string takes almost anything.
  730. return (1, $opt,$arg,$dsttype,$incr,$key)
  731. if defined $optarg || defined $rest;
  732. return (1, $opt,$arg,$dsttype,$incr,$key) if $arg eq "-"; # ??
  733. # Check for option or option list terminator.
  734. if ($arg eq $argend ||
  735. $arg =~ /^$prefix.+/) {
  736. # Push back.
  737. unshift (@ARGV, $arg);
  738. # Supply empty value.
  739. $arg = '';
  740. }
  741. }
  742. elsif ( $type eq "n" || $type eq "i" ) { # numeric/integer
  743. if ( $bundling && defined $rest && $rest =~ /^([-+]?[0-9]+)(.*)$/s ) {
  744. $arg = $1;
  745. $rest = $2;
  746. unshift (@ARGV, $starter.$rest) if defined $rest && $rest ne '';
  747. }
  748. elsif ( $arg !~ /^[-+]?[0-9]+$/ ) {
  749. if ( defined $optarg || $mand eq "=" ) {
  750. if ( $passthrough ) {
  751. unshift (@ARGV, defined $rest ? $starter.$rest : $arg)
  752. unless defined $optarg;
  753. return (0);
  754. }
  755. warn ("Value \"", $arg, "\" invalid for option ",
  756. $opt, " (number expected)\n");
  757. $error++;
  758. undef $opt;
  759. # Push back.
  760. unshift (@ARGV, $starter.$rest) if defined $rest;
  761. }
  762. else {
  763. # Push back.
  764. unshift (@ARGV, defined $rest ? $starter.$rest : $arg);
  765. # Supply default value.
  766. $arg = 0;
  767. }
  768. }
  769. }
  770. elsif ( $type eq "f" ) { # real number, int is also ok
  771. # We require at least one digit before a point or 'e',
  772. # and at least one digit following the point and 'e'.
  773. # [-]NN[.NN][eNN]
  774. if ( $bundling && defined $rest &&
  775. $rest =~ /^([-+]?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?)(.*)$/s ) {
  776. $arg = $1;
  777. $rest = $+;
  778. unshift (@ARGV, $starter.$rest) if defined $rest && $rest ne '';
  779. }
  780. elsif ( $arg !~ /^[-+]?[0-9.]+(\.[0-9]+)?([eE][-+]?[0-9]+)?$/ ) {
  781. if ( defined $optarg || $mand eq "=" ) {
  782. if ( $passthrough ) {
  783. unshift (@ARGV, defined $rest ? $starter.$rest : $arg)
  784. unless defined $optarg;
  785. return (0);
  786. }
  787. warn ("Value \"", $arg, "\" invalid for option ",
  788. $opt, " (real number expected)\n");
  789. $error++;
  790. undef $opt;
  791. # Push back.
  792. unshift (@ARGV, $starter.$rest) if defined $rest;
  793. }
  794. else {
  795. # Push back.
  796. unshift (@ARGV, defined $rest ? $starter.$rest : $arg);
  797. # Supply default value.
  798. $arg = 0.0;
  799. }
  800. }
  801. }
  802. else {
  803. Croak ("GetOpt::Long internal error (Can't happen)\n");
  804. }
  805. return (1, $opt, $arg, $dsttype, $incr, $key);
  806. }
  807. # Getopt::Long Configuration.
  808. sub Configure (@) {
  809. my (@options) = @_;
  810. my $prevconfig =
  811. [ $error, $debug, $major_version, $minor_version,
  812. $autoabbrev, $getopt_compat, $ignorecase, $bundling, $order,
  813. $gnu_compat, $passthrough, $genprefix ];
  814. if ( ref($options[0]) eq 'ARRAY' ) {
  815. ( $error, $debug, $major_version, $minor_version,
  816. $autoabbrev, $getopt_compat, $ignorecase, $bundling, $order,
  817. $gnu_compat, $passthrough, $genprefix ) = @{shift(@options)};
  818. }
  819. my $opt;
  820. foreach $opt ( @options ) {
  821. my $try = lc ($opt);
  822. my $action = 1;
  823. if ( $try =~ /^no_?(.*)$/s ) {
  824. $action = 0;
  825. $try = $+;
  826. }
  827. if ( ($try eq 'default' or $try eq 'defaults') && $action ) {
  828. ConfigDefaults ();
  829. }
  830. elsif ( ($try eq 'posix_default' or $try eq 'posix_defaults') ) {
  831. local $ENV{POSIXLY_CORRECT};
  832. $ENV{POSIXLY_CORRECT} = 1 if $action;
  833. ConfigDefaults ();
  834. }
  835. elsif ( $try eq 'auto_abbrev' or $try eq 'autoabbrev' ) {
  836. $autoabbrev = $action;
  837. }
  838. elsif ( $try eq 'getopt_compat' ) {
  839. $getopt_compat = $action;
  840. }
  841. elsif ( $try eq 'gnu_getopt' ) {
  842. if ( $action ) {
  843. $gnu_compat = 1;
  844. $bundling = 1;
  845. $getopt_compat = 0;
  846. $permute = 1;
  847. }
  848. }
  849. elsif ( $try eq 'gnu_compat' ) {
  850. $gnu_compat = $action;
  851. }
  852. elsif ( $try eq 'ignorecase' or $try eq 'ignore_case' ) {
  853. $ignorecase = $action;
  854. }
  855. elsif ( $try eq 'ignore_case_always' ) {
  856. $ignorecase = $action ? 2 : 0;
  857. }
  858. elsif ( $try eq 'bundling' ) {
  859. $bundling = $action;
  860. }
  861. elsif ( $try eq 'bundling_override' ) {
  862. $bundling = $action ? 2 : 0;
  863. }
  864. elsif ( $try eq 'require_order' ) {
  865. $order = $action ? $REQUIRE_ORDER : $PERMUTE;
  866. }
  867. elsif ( $try eq 'permute' ) {
  868. $order = $action ? $PERMUTE : $REQUIRE_ORDER;
  869. }
  870. elsif ( $try eq 'pass_through' or $try eq 'passthrough' ) {
  871. $passthrough = $action;
  872. }
  873. elsif ( $try =~ /^prefix=(.+)$/ && $action ) {
  874. $genprefix = $1;
  875. # Turn into regexp. Needs to be parenthesized!
  876. $genprefix = "(" . quotemeta($genprefix) . ")";
  877. eval { '' =~ /$genprefix/; };
  878. Croak ("Getopt::Long: invalid pattern \"$genprefix\"") if $@;
  879. }
  880. elsif ( $try =~ /^prefix_pattern=(.+)$/ && $action ) {
  881. $genprefix = $1;
  882. # Parenthesize if needed.
  883. $genprefix = "(" . $genprefix . ")"
  884. unless $genprefix =~ /^\(.*\)$/;
  885. eval { '' =~ /$genprefix/; };
  886. Croak ("Getopt::Long: invalid pattern \"$genprefix\"") if $@;
  887. }
  888. elsif ( $try eq 'debug' ) {
  889. $debug = $action;
  890. }
  891. else {
  892. Croak ("Getopt::Long: unknown config parameter \"$opt\"")
  893. }
  894. }
  895. $prevconfig;
  896. }
  897. # Deprecated name.
  898. sub config (@) {
  899. Configure (@_);
  900. }
  901. # To prevent Carp from being loaded unnecessarily.
  902. sub Croak (@) {
  903. require 'Carp.pm';
  904. $Carp::CarpLevel = 1;
  905. Carp::croak(@_);
  906. };
  907. ################ Documentation ################
  908. =head1 NAME
  909. Getopt::Long - Extended processing of command line options
  910. =head1 SYNOPSIS
  911. use Getopt::Long;
  912. $result = GetOptions (...option-descriptions...);
  913. =head1 DESCRIPTION
  914. The Getopt::Long module implements an extended getopt function called
  915. GetOptions(). This function adheres to the POSIX syntax for command
  916. line options, with GNU extensions. In general, this means that options
  917. have long names instead of single letters, and are introduced with a
  918. double dash "--". Support for bundling of command line options, as was
  919. the case with the more traditional single-letter approach, is provided
  920. but not enabled by default.
  921. =head1 Command Line Options, an Introduction
  922. Command line operated programs traditionally take their arguments from
  923. the command line, for example filenames or other information that the
  924. program needs to know. Besides arguments, these programs often take
  925. command line I<options> as well. Options are not necessary for the
  926. program to work, hence the name 'option', but are used to modify its
  927. default behaviour. For example, a program could do its job quietly,
  928. but with a suitable option it could provide verbose information about
  929. what it did.
  930. Command line options come in several flavours. Historically, they are
  931. preceded by a single dash C<->, and consist of a single letter.
  932. -l -a -c
  933. Usually, these single-character options can be bundled:
  934. -lac
  935. Options can have values, the value is placed after the option
  936. character. Sometimes with whitespace in between, sometimes not:
  937. -s 24 -s24
  938. Due to the very cryptic nature of these options, another style was
  939. developed that used long names. So instead of a cryptic C<-l> one
  940. could use the more descriptive C<--long>. To distinguish between a
  941. bundle of single-character options and a long one, two dashes are used
  942. to precede the option name. Early implementations of long options used
  943. a plus C<+> instead. Also, option values could be specified either
  944. like
  945. --size=24
  946. or
  947. --size 24
  948. The C<+> form is now obsolete and strongly deprecated.
  949. =head1 Getting Started with Getopt::Long
  950. Getopt::Long is the Perl5 successor of C<newgetopt.pl>. This was
  951. the first Perl module that provided support for handling the new style
  952. of command line options, hence the name Getopt::Long. This module
  953. also supports single-character options and bundling. In this case, the
  954. options are restricted to alphabetic characters only, and the
  955. characters C<?> and C<->.
  956. To use Getopt::Long from a Perl program, you must include the
  957. following line in your Perl program:
  958. use Getopt::Long;
  959. This will load the core of the Getopt::Long module and prepare your
  960. program for using it. Most of the actual Getopt::Long code is not
  961. loaded until you really call one of its functions.
  962. In the default configuration, options names may be abbreviated to
  963. uniqueness, case does not matter, and a single dash is sufficient,
  964. even for long option names. Also, options may be placed between
  965. non-option arguments. See L<Configuring Getopt::Long> for more
  966. details on how to configure Getopt::Long.
  967. =head2 Simple options
  968. The most simple options are the ones that take no values. Their mere
  969. presence on the command line enables the option. Popular examples are:
  970. --all --verbose --quiet --debug
  971. Handling simple options is straightforward:
  972. my $verbose = ''; # option variable with default value (false)
  973. my $all = ''; # option variable with default value (false)
  974. GetOptions ('verbose' => \$verbose, 'all' => \$all);
  975. The call to GetOptions() parses the command line arguments that are
  976. present in C<@ARGV> and sets the option variable to the value C<1> if
  977. the option did occur on the command line. Otherwise, the option
  978. variable is not touched. Setting the option value to true is often
  979. called I<enabling> the option.
  980. The option name as specified to the GetOptions() function is called
  981. the option I<specification>. Later we'll see that this specification
  982. can contain more than just the option name. The reference to the
  983. variable is called the option I<destination>.
  984. GetOptions() will return a true value if the command line could be
  985. processed successfully. Otherwise, it will write error messages to
  986. STDERR, and return a false result.
  987. =head2 A little bit less simple options
  988. Getopt::Long supports two useful variants of simple options:
  989. I<negatable> options and I<incremental> options.
  990. A negatable option is specified with a exclamation mark C<!> after the
  991. option name:
  992. my $verbose = ''; # option variable with default value (false)
  993. GetOptions ('verbose!' => \$verbose);
  994. Now, using C<--verbose> on the command line will enable C<$verbose>,
  995. as expected. But it is also allowed to use C<--noverbose>, which will
  996. disable C<$verbose> by setting its value to C<0>. Using a suitable
  997. default value, the program can find out whether C<$verbose> is false
  998. by default, or disabled by using C<--noverbose>.
  999. An incremental option is specified with a plus C<+> after the
  1000. option name:
  1001. my $verbose = ''; # option variable with default value (false)
  1002. GetOptions ('verbose+' => \$verbose);
  1003. Using C<--verbose> on the command line will increment the value of
  1004. C<$verbose>. This way the program can keep track of how many times the
  1005. option occurred on the command line. For example, each occurrence of
  1006. C<--verbose> could increase the verbosity level of the program.
  1007. =head2 Mixing command line option with other arguments
  1008. Usually programs take command line options as well as other arguments,
  1009. for example, file names. It is good practice to always specify the
  1010. options first, and the other arguments last. Getopt::Long will,
  1011. however, allow the options and arguments to be mixed and 'filter out'
  1012. all the options before passing the rest of the arguments to the
  1013. program. To stop Getopt::Long from processing further arguments,
  1014. insert a double dash C<--> on the command line:
  1015. --size 24 -- --all
  1016. In this example, C<--all> will I<not> be treated as an option, but
  1017. passed to the program unharmed, in C<@ARGV>.
  1018. =head2 Options with values
  1019. For options that take values it must be specified whether the option
  1020. value is required or not, and what kind of value the option expects.
  1021. Three kinds of values are supported: integer numbers, floating point
  1022. numbers, and strings.
  1023. If the option value is required, Getopt::Long will take the
  1024. command line argument that follows the option and assign this to the
  1025. option variable. If, however, the option value is specified as
  1026. optional, this will only be done if that value does not look like a
  1027. valid command line option itself.
  1028. my $tag = ''; # option variable with default value
  1029. GetOptions ('tag=s' => \$tag);
  1030. In the option specification, the option name is followed by an equals
  1031. sign C<=> and the letter C<s>. The equals sign indicates that this
  1032. option requires a value. The letter C<s> indicates that this value is
  1033. an arbitrary string. Other possible value types are C<i> for integer
  1034. values, and C<f> for floating point values. Using a colon C<:> instead
  1035. of the equals sign indicates that the option value is optional. In
  1036. this case, if no suitable value is supplied, string valued options get
  1037. an empty string C<''> assigned, while numeric options are set to C<0>.
  1038. =head2 Options with multiple values
  1039. Options sometimes take several values. For example, a program could
  1040. use multiple directories to search for library files:
  1041. --library lib/stdlib --library lib/extlib
  1042. To accomplish this behaviour, simply specify an array reference as the
  1043. destination for the option:
  1044. my @libfiles = ();
  1045. GetOptions ("library=s" => \@libfiles);
  1046. Used with the example above, C<@libfiles> would contain two strings
  1047. upon completion: C<"lib/srdlib"> and C<"lib/extlib">, in that order.
  1048. It is also possible to specify that only integer or floating point
  1049. numbers are acceptible values.
  1050. Often it is useful to allow comma-separated lists of values as well as
  1051. multiple occurrences of the options. This is easy using Perl's split()
  1052. and join() operators:
  1053. my @libfiles = ();
  1054. GetOptions ("library=s" => \@libfiles);
  1055. @libfiles = split(/,/,join(',',@libfiles));
  1056. Of course, it is important to choose the right separator string for
  1057. each purpose.
  1058. =head2 Options with hash values
  1059. If the option destination is a reference to a hash, the option will
  1060. take, as value, strings of the form I<key>C<=>I<value>. The value will
  1061. be stored with the specified key in the hash.
  1062. my %defines = ();
  1063. GetOptions ("define=s" => \%defines);
  1064. When used with command line options:
  1065. --define os=linux --define vendor=redhat
  1066. the hash C<%defines> will contain two keys, C<"os"> with value
  1067. C<"linux> and C<"vendor"> with value C<"redhat">.
  1068. It is also possible to specify that only integer or floating point
  1069. numbers are acceptible values. The keys are always taken to be strings.
  1070. =head2 User-defined subroutines to handle options
  1071. Ultimate control over what should be done when (actually: each time)
  1072. an option is encountered on the command line can be achieved by
  1073. designating a reference to a subroutine (or an anonymous subroutine)
  1074. as the option destination. When GetOptions() encounters the option, it
  1075. will call the subroutine with two arguments: the name of the option,
  1076. and the value to be assigned. It is up to the subroutine to store the
  1077. value, or do whatever it thinks is appropriate.
  1078. A trivial application of this mechanism is to implement options that
  1079. are related to each other. For example:
  1080. my $verbose = ''; # option variable with default value (false)
  1081. GetOptions ('verbose' => \$verbose,
  1082. 'quiet' => sub { $verbose = 0 });
  1083. Here C<--verbose> and C<--quiet> control the same variable
  1084. C<$verbose>, but with opposite values.
  1085. If the subroutine needs to signal an error, it should call die() with
  1086. the desired error message as its argument. GetOptions() will catch the
  1087. die(), issue the error message, and record that an error result must
  1088. be returned upon completion.
  1089. If the text of the error message starts with an exclamantion mark C<!>
  1090. it is interpreted specially by GetOptions(). There is currently one
  1091. special command implemented: C<die("!FINISH")> will cause GetOptions()
  1092. to stop processing options, as if it encountered a double dash C<-->.
  1093. =head2 Options with multiple names
  1094. Often it is user friendly to supply alternate mnemonic names for
  1095. options. For example C<--height> could be an alternate name for
  1096. C<--length>. Alternate names can be included in the option
  1097. specification, separated by vertical bar C<|> characters. To implement
  1098. the above example:
  1099. GetOptions ('length|height=f' => \$length);
  1100. The first name is called the I<primary> name, the other names are
  1101. called I<aliases>.
  1102. Multiple alternate names are possible.
  1103. =head2 Case and abbreviations
  1104. Without additional configuration, GetOptions() will ignore the case of
  1105. option names, and allow the options to be abbreviated to uniqueness.
  1106. GetOptions ('length|height=f' => \$length, "head" => \$head);
  1107. This call will allow C<--l> and C<--L> for the length option, but
  1108. requires a least C<--hea> and C<--hei> for the head and height options.
  1109. =head2 Summary of Option Specifications
  1110. Each option specifier consists of two parts: the name specification
  1111. and the argument specification.
  1112. The name specification contains the name of the option, optionally
  1113. followed by a list of alternative names separated by vertical bar
  1114. characters.
  1115. length option name is "length"
  1116. length|size|l name is "length", aliases are "size" and "l"
  1117. The argument specification is optional. If omitted, the option is
  1118. considered boolean, a value of 1 will be assigned when the option is
  1119. used on the command line.
  1120. The argument specification can be
  1121. =over
  1122. =item !
  1123. The option does not take an argument and may be negated, i.e. prefixed
  1124. by "no". E.g. C<"foo!"> will allow C<--foo> (a value of 1 will be
  1125. assigned) and C<--nofoo> (a value of 0 will be assigned). If the
  1126. option has aliases, this applies to the aliases as well.
  1127. Using negation on a single letter option when bundling is in effect is
  1128. pointless and will result in a warning.
  1129. =item +
  1130. The option does not take an argument and will be incremented by 1
  1131. every time it appears on the command line. E.g. C<"more+">, when used
  1132. with C<--more --more --more>, will increment the value three times,
  1133. resulting in a value of 3 (provided it was 0 or undefined at first).
  1134. The C<+> specifier is ignored if the option destination is not a scalar.
  1135. =item = I<type> [ I<desttype> ]
  1136. The option requires an argument of the given type. Supported types
  1137. are:
  1138. =over
  1139. =item s
  1140. String. An arbitrary sequence of characters. It is valid for the
  1141. argument to start with C<-> or C<-->.
  1142. =item i
  1143. Integer. An optional leading plus or minus sign, followed by a
  1144. sequence of digits.
  1145. =item f
  1146. Real number. For example C<3.14>, C<-6.23E24> and so on.
  1147. =back
  1148. The I<desttype> can be C<@> or C<%> to specify that the option is
  1149. list or a hash valued. This is only needed when the destination for
  1150. the option value is not otherwise specified. It should be omitted when
  1151. not needed.
  1152. =item : I<type> [ I<desttype> ]
  1153. Like C<=>, but designates the argument as optional.
  1154. If omitted, an empty string will be assigned to string values options,
  1155. and the value zero to numeric options.
  1156. Note that if a string argument starts with C<-> or C<-->, it will be
  1157. considered an option on itself.
  1158. =back
  1159. =head1 Advanced Possibilities
  1160. =head2 Object oriented interface
  1161. Getopt::Long can be used in an object oriented way as well:
  1162. use Getopt::Long;
  1163. $p = new Getopt::Long::Parser;
  1164. $p->configure(...configuration options...);
  1165. if ($p->getoptions(...options descriptions...)) ...
  1166. Configuration options can be passed to the constructor:
  1167. $p = new Getopt::Long::Parser
  1168. config => [...configuration options...];
  1169. For thread safety, each method call will acquire an exclusive lock to
  1170. the Getopt::Long module. So don't call these methods from a callback
  1171. routine!
  1172. =head2 Documentation and help texts
  1173. Getopt::Long encourages the use of Pod::Usage to produce help
  1174. messages. For example:
  1175. use Getopt::Long;
  1176. use Pod::Usage;
  1177. my $man = 0;
  1178. my $help = 0;
  1179. GetOptions('help|?' => \$help, man => \$man) or pod2usage(2);
  1180. pod2usage(1) if $help;
  1181. pod2usage(-exitstatus => 0, -verbose => 2) if $man;
  1182. __END__
  1183. =head1 NAME
  1184. sample - Using GetOpt::Long and Pod::Usage
  1185. =head1 SYNOPSIS
  1186. sample [options] [file ...]
  1187. Options:
  1188. -help brief help message
  1189. -man full documentation
  1190. =head1 OPTIONS
  1191. =over 8
  1192. =item B<-help>
  1193. Print a brief help message and exits.
  1194. =item B<-man>
  1195. Prints the manual page and exits.
  1196. =back
  1197. =head1 DESCRIPTION
  1198. B<This program> will read the given input file(s) and do someting
  1199. useful with the contents thereof.
  1200. =cut
  1201. See L<Pod::Usage> for details.
  1202. =head2 Storing options in a hash
  1203. Sometimes, for example when there are a lot of options, having a
  1204. separate variable for each of them can be cumbersome. GetOptions()
  1205. supports, as an alternative mechanism, storing options in a hash.
  1206. To obtain this, a reference to a hash must be passed I<as the first
  1207. argument> to GetOptions(). For each option that is specified on the
  1208. command line, the option value will be stored in the hash with the
  1209. option name as key. Options that are not actually used on the command
  1210. line will not be put in the hash, on other words,
  1211. C<exists($h{option})> (or defined()) can be used to test if an option
  1212. was used. The drawback is that warnings will be issued if the program
  1213. runs under C<use strict> and uses C<$h{option}> without testing with
  1214. exists() or defined() first.
  1215. my %h = ();
  1216. GetOptions (\%h, 'length=i'); # will store in $h{length}
  1217. For options that take list or hash values, it is necessary to indicate
  1218. this by appending an C<@> or C<%> sign after the type:
  1219. GetOptions (\%h, 'colours=s@'); # will push to @{$h{colours}}
  1220. To make things more complicated, the hash may contain references to
  1221. the actual destinations, for example:
  1222. my $len = 0;
  1223. my %h = ('length' => \$len);
  1224. GetOptions (\%h, 'length=i'); # will store in $len
  1225. This example is fully equivalent with:
  1226. my $len = 0;
  1227. GetOptions ('length=i' => \$len); # will store in $len
  1228. Any mixture is possible. For example, the most frequently used options
  1229. could be stored in variables while all other options get stored in the
  1230. hash:
  1231. my $verbose = 0; # frequently referred
  1232. my $debug = 0; # frequently referred
  1233. my %h = ('verbose' => \$verbose, 'debug' => \$debug);
  1234. GetOptions (\%h, 'verbose', 'debug', 'filter', 'size=i');
  1235. if ( $verbose ) { ... }
  1236. if ( exists $h{filter} ) { ... option 'filter' was specified ... }
  1237. =head2 Bundling
  1238. With bundling it is possible to set several single-character options
  1239. at once. For example if C<a>, C<v> and C<x> are all valid options,
  1240. -vax
  1241. would set all three.
  1242. Getopt::Long supports two levels of bundling. To enable bundling, a
  1243. call to Getopt::Long::Configure is required.
  1244. The first level of bundling can be enabled with:
  1245. Getopt::Long::Configure ("bundling");
  1246. Configured this way, single-character options can be bundled but long
  1247. options B<must> always start with a double dash C<--> to avoid
  1248. abiguity. For example, when C<vax>, C<a>, C<v> and C<x> are all valid
  1249. options,
  1250. -vax
  1251. would set C<a>, C<v> and C<x>, but
  1252. --vax
  1253. would set C<vax>.
  1254. The second level of bundling lifts this restriction. It can be enabled
  1255. with:
  1256. Getopt::Long::Configure ("bundling_override");
  1257. Now, C<-vax> would set the option C<vax>.
  1258. When any level of bundling is enabled, option values may be inserted
  1259. in the bundle. For example:
  1260. -h24w80
  1261. is equivalent to
  1262. -h 24 -w 80
  1263. When configured for bundling, single-character options are matched
  1264. case sensitive while long options are matched case insensitive. To
  1265. have the single-character options matched case insensitive as well,
  1266. use:
  1267. Getopt::Long::Configure ("bundling", "ignorecase_always");
  1268. It goes without saying that bundling can be quite confusing.
  1269. =head2 The lonesome dash
  1270. Normally, a lone dash C<-> on the command line will not be considered
  1271. an option. Option processing will terminate (unless "permute" is
  1272. configured) and the dash will be left in C<@ARGV>.
  1273. It is possible to get special treatment for a lone dash. This can be
  1274. achieved by adding an option specification with an empty name, for
  1275. example:
  1276. GetOptions ('' => \$stdio);
  1277. A lone dash on the command line will now be a legal option, and using
  1278. it will set variable C<$stdio>.
  1279. =head2 Argument call-back
  1280. A special option 'name' C<<>> can be used to designate a subroutine
  1281. to handle non-option arguments. When GetOptions() encounters an
  1282. argument that does not look like an option, it will immediately call this
  1283. subroutine and passes it the argument as a parameter.
  1284. For example:
  1285. my $width = 80;
  1286. sub process { ... }
  1287. GetOptions ('width=i' => \$width, '<>' => \&process);
  1288. When applied to the following command line:
  1289. arg1 --width=72 arg2 --width=60 arg3
  1290. This will call
  1291. C<process("arg1")> while C<$width> is C<80>,
  1292. C<process("arg2")> while C<$width> is C<72>, and
  1293. C<process("arg3")> while C<$width> is C<60>.
  1294. This feature requires configuration option B<permute>, see section
  1295. L<Configuring Getopt::Long>.
  1296. =head1 Configuring Getopt::Long
  1297. Getopt::Long can be configured by calling subroutine
  1298. Getopt::Long::Configure(). This subroutine takes a list of quoted
  1299. strings, each specifying a configuration option to be enabled, e.g.
  1300. C<ignore_case>, or disabled, e.g. C<no_ignore_case>. Case does not
  1301. matter. Multiple calls to Configure() are possible.
  1302. Alternatively, as of version 2.24, the configuration options may be
  1303. passed together with the C<use> statement:
  1304. use Getopt::Long qw(:config no_ignore_case bundling);
  1305. The following options are available:
  1306. =over 12
  1307. =item default
  1308. This option causes all configuration options to be reset to their
  1309. default values.
  1310. =item posix_default
  1311. This option causes all configuration options to be reset to their
  1312. default values as if the environment variable POSIXLY_CORRECT had
  1313. been set.
  1314. =item auto_abbrev
  1315. Allow option names to be abbreviated to uniqueness.
  1316. Default is enabled unless environment variable
  1317. POSIXLY_CORRECT has been set, in which case C<auto_abbrev> is disabled.
  1318. =item getopt_compat
  1319. Allow C<+> to start options.
  1320. Default is enabled unless environment variable
  1321. POSIXLY_CORRECT has been set, in which case C<getopt_compat> is disabled.
  1322. =item gnu_compat
  1323. C<gnu_compat> controls whether C<--opt=> is allowed, and what it should
  1324. do. Without C<gnu_compat>, C<--opt=> gives an error. With C<gnu_compat>,
  1325. C<--opt=> will give option C<opt> and empty value.
  1326. This is the way GNU getopt_long() does it.
  1327. =item gnu_getopt
  1328. This is a short way of setting C<gnu_compat> C<bundling> C<permute>
  1329. C<no_getopt_compat>. With C<gnu_getopt>, command line handling should be
  1330. fully compatible with GNU getopt_long().
  1331. =item require_order
  1332. Whether command line arguments are allowed to be mixed with options.
  1333. Default is disabled unless environment variable
  1334. POSIXLY_CORRECT has been set, in which case C<require_order> is enabled.
  1335. See also C<permute>, which is the opposite of C<require_order>.
  1336. =item permute
  1337. Whether command line arguments are allowed to be mixed with options.
  1338. Default is enabled unless environment variable
  1339. POSIXLY_CORRECT has been set, in which case C<permute> is disabled.
  1340. Note that C<permute> is the opposite of C<require_order>.
  1341. If C<permute> is enabled, this means that
  1342. --foo arg1 --bar arg2 arg3
  1343. is equivalent to
  1344. --foo --bar arg1 arg2 arg3
  1345. If an argument call-back routine is specified, C<@ARGV> will always be
  1346. empty upon succesful return of GetOptions() since all options have been
  1347. processed. The only exception is when C<--> is used:
  1348. --foo arg1 --bar arg2 -- arg3
  1349. will call the call-back routine for arg1 and arg2, and terminate
  1350. GetOptions() leaving C<"arg2"> in C<@ARGV>.
  1351. If C<require_order> is enabled, options processing
  1352. terminates when the first non-option is encountered.
  1353. --foo arg1 --bar arg2 arg3
  1354. is equivalent to
  1355. --foo -- arg1 --bar arg2 arg3
  1356. If C<pass_through> is also enabled, options processing will terminate
  1357. at the first unrecognized option, or non-option, whichever comes
  1358. first.
  1359. =item bundling (default: disabled)
  1360. Enabling this option will allow single-character options to be bundled.
  1361. To distinguish bundles from long option names, long options I<must> be
  1362. introduced with C<--> and single-character options (and bundles) with
  1363. C<->.
  1364. Note: disabling C<bundling> also disables C<bundling_override>.
  1365. =item bundling_override (default: disabled)
  1366. If C<bundling_override> is enabled, bundling is enabled as with
  1367. C<bundling> but now long option names override option bundles.
  1368. Note: disabling C<bundling_override> also disables C<bundling>.
  1369. B<Note:> Using option bundling can easily lead to unexpected results,
  1370. especially when mixing long options and bundles. Caveat emptor.
  1371. =item ignore_case (default: enabled)
  1372. If enabled, case is ignored when matching long option names. Single
  1373. character options will be treated case-sensitive.
  1374. Note: disabling C<ignore_case> also disables C<ignore_case_always>.
  1375. =item ignore_case_always (default: disabled)
  1376. When bundling is in effect, case is ignored on single-character
  1377. options also.
  1378. Note: disabling C<ignore_case_always> also disables C<ignore_case>.
  1379. =item pass_through (default: disabled)
  1380. Options that are unknown, ambiguous or supplied with an invalid option
  1381. value are passed through in C<@ARGV> instead of being flagged as
  1382. errors. This makes it possible to write wrapper scripts that process
  1383. only part of the user supplied command line arguments, and pass the
  1384. remaining options to some other program.
  1385. If C<require_order> is enabled, options processing will terminate at
  1386. the first unrecognized option, or non-option, whichever comes first.
  1387. However, if C<permute> is enabled instead, results can become confusing.
  1388. =item prefix
  1389. The string that starts options. If a constant string is not
  1390. sufficient, see C<prefix_pattern>.
  1391. =item prefix_pattern
  1392. A Perl pattern that identifies the strings that introduce options.
  1393. Default is C<(--|-|\+)> unless environment variable
  1394. POSIXLY_CORRECT has been set, in which case it is C<(--|-)>.
  1395. =item debug (default: disabled)
  1396. Enable debugging output.
  1397. =back
  1398. =head1 Return values and Errors
  1399. Configuration errors and errors in the option definitions are
  1400. signalled using die() and will terminate the calling program unless
  1401. the call to Getopt::Long::GetOptions() was embedded in C<eval { ...
  1402. }>, or die() was trapped using C<$SIG{__DIE__}>.
  1403. GetOptions returns true to indicate success.
  1404. It returns false when the function detected one or more errors during
  1405. option parsing. These errors are signalled using warn() and can be
  1406. trapped with C<$SIG{__WARN__}>.
  1407. Errors that can't happen are signalled using Carp::croak().
  1408. =head1 Legacy
  1409. The earliest development of C<newgetopt.pl> started in 1990, with Perl
  1410. version 4. As a result, its development, and the development of
  1411. Getopt::Long, has gone through several stages. Since backward
  1412. compatibility has always been extremely important, the current version
  1413. of Getopt::Long still supports a lot of constructs that nowadays are
  1414. no longer necessary or otherwise unwanted. This section describes
  1415. briefly some of these 'features'.
  1416. =head2 Default destinations
  1417. When no destination is specified for an option, GetOptions will store
  1418. the resultant value in a global variable named C<opt_>I<XXX>, where
  1419. I<XXX> is the primary name of this option. When a progam executes
  1420. under C<use strict> (recommended), these variables must be
  1421. pre-declared with our() or C<use vars>.
  1422. our $opt_length = 0;
  1423. GetOptions ('length=i'); # will store in $opt_length
  1424. To yield a usable Perl variable, characters that are not part of the
  1425. syntax for variables are translated to underscores. For example,
  1426. C<--fpp-struct-return> will set the variable
  1427. C<$opt_fpp_struct_return>. Note that this variable resides in the
  1428. namespace of the calling program, not necessarily C<main>. For
  1429. example:
  1430. GetOptions ("size=i", "sizes=i@");
  1431. with command line "-size 10 -sizes 24 -sizes 48" will perform the
  1432. equivalent of the assignments
  1433. $opt_size = 10;
  1434. @opt_sizes = (24, 48);
  1435. =head2 Alternative option starters
  1436. A string of alternative option starter characters may be passed as the
  1437. first argument (or the first argument after a leading hash reference
  1438. argument).
  1439. my $len = 0;
  1440. GetOptions ('/', 'length=i' => $len);
  1441. Now the command line may look like:
  1442. /length 24 -- arg
  1443. Note that to terminate options processing still requires a double dash
  1444. C<-->.
  1445. GetOptions() will not interpret a leading C<< "<>" >> as option starters
  1446. if the next argument is a reference. To force C<< "<" >> and C<< ">" >> as
  1447. option starters, use C<< "><" >>. Confusing? Well, B<using a starter
  1448. argument is strongly deprecated> anyway.
  1449. =head2 Configuration variables
  1450. Previous versions of Getopt::Long used variables for the purpose of
  1451. configuring. Although manipulating these variables still work, it is
  1452. strongly encouraged to use the C<Configure> routine that was introduced
  1453. in version 2.17. Besides, it is much easier.
  1454. =head1 Trouble Shooting
  1455. =head2 Warning: Ignoring '!' modifier for short option
  1456. This warning is issued when the '!' modifier is applied to a short
  1457. (one-character) option and bundling is in effect. E.g.,
  1458. Getopt::Long::Configure("bundling");
  1459. GetOptions("foo|f!" => \$foo);
  1460. Note that older Getopt::Long versions did not issue a warning, because
  1461. the '!' modifier was applied to the first name only. This bug was
  1462. fixed in 2.22.
  1463. Solution: separate the long and short names and apply the '!' to the
  1464. long names only, e.g.,
  1465. GetOptions("foo!" => \$foo, "f" => \$foo);
  1466. =head2 GetOptions does not return a false result when an option is not supplied
  1467. That's why they're called 'options'.
  1468. =head1 AUTHOR
  1469. Johan Vromans <[email protected]>
  1470. =head1 COPYRIGHT AND DISCLAIMER
  1471. This program is Copyright 2000,1990 by Johan Vromans.
  1472. This program is free software; you can redistribute it and/or
  1473. modify it under the terms of the Perl Artistic License or the
  1474. GNU General Public License as published by the Free Software
  1475. Foundation; either version 2 of the License, or (at your option) any
  1476. later version.
  1477. This program is distributed in the hope that it will be useful,
  1478. but WITHOUT ANY WARRANTY; without even the implied warranty of
  1479. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  1480. GNU General Public License for more details.
  1481. If you do not have a copy of the GNU General Public License write to
  1482. the Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
  1483. MA 02139, USA.
  1484. =cut
  1485. # Local Variables:
  1486. # eval: (load-file "pod.el")
  1487. # End: