]>
git.saurik.com Git - apple/javascriptcore.git/blob - tests/mozilla/Getopt/Mixed.pm
1 #---------------------------------------------------------------------
4 # Copyright 1995 Christopher J. Madsen
6 # Author: Christopher J. Madsen <ac608@yfn.ysu.edu>
8 # Version: $Revision: 1.8 $ ($Date: 1996/02/09 00:05:00 $)
9 # Note that RCS revision 1.23 => $Getopt::Mixed::VERSION = "1.023"
11 # This program is free software; you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 2, or (at your option)
16 # This program is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
21 # You should have received a copy of the GNU General Public License
22 # along with Perl; see the file COPYING. If not, write to the
23 # Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
25 # Process both single-character and extended options
26 #---------------------------------------------------------------------
34 @EXPORT_OK = qw(abortMsg getOptions nextOption);
36 #=====================================================================
37 # Package Global Variables:
41 # The permissible settings for $order:
46 # Regular expressions:
47 $intRegexp = '^[-+]?\d+$'; # Match an integer
48 $floatRegexp = '^[-+]?(\d*\.?\d+|\d+\.)$'; # Match a real number
49 $typeChars = 'sif'; # Match type characters
51 # Convert RCS revision number (must be main branch) to d.ddd format:
52 ' $Revision: 1.8 $ ' =~ / (\d+)\.(\d{1,3}) /
53 or die "Invalid version number";
54 $VERSION = sprintf("%d.%03d",$1,$2);
57 #=====================================================================
59 #---------------------------------------------------------------------
60 # Initialize the option processor:
62 # You should set any customization variables *after* calling init.
64 # For a description of option declarations, see the documentation at
65 # the end of this file.
68 # List of option declarations (separated by whitespace)
69 # If the first argument is entirely non-alphanumeric characters
70 # with no whitespace, it is the characters that start options.
77 $ignoreCase = 1; # Ignore case by default
78 $optionStart = "-"; # Dash is the default option starter
80 # If the first argument is entirely non-alphanumeric characters
81 # with no whitespace, it is the desired value for $optionStart:
82 $optionStart = shift @_ if $_[0] =~ /^[^a-z0-9\s]+$/i;
85 # Ignore case unless there are upper-case options:
86 $ignoreCase = 0 if $group =~ /[A-Z]/;
87 foreach $option (split(/\s+/,$group)) {
88 croak
"Invalid option declaration `$option'"
89 unless $option =~ /^([^=:>]+)([=:][$typeChars]|>[^=:>]+)?$/o;
92 if ($type =~ /^>(.*)$/) {
94 croak
"Invalid synonym `$option'"
95 if (not defined $options{$type}
96 or $options{$type} =~ /^[^:=]/);
98 $options{$opt} = $type;
99 } # end foreach option
100 } # end foreach group
102 # Handle POSIX compliancy:
103 if (defined $ENV{"POSIXLY_CORRECT"}) {
104 $order = $REQUIRE_ORDER;
110 $badOption = \
&badOption
;
111 $checkArg = \
&checkArg
;
114 #---------------------------------------------------------------------
115 # Clean up when we're done:
117 # This just releases the memory used by the %options hash.
119 # If 'help' was defined as an option, a new hash with just 'help' is
120 # created, in case the program calls abortMsg.
124 my $help = defined($options{'help'});
126 $options{'help'} = "" if $help;
129 #---------------------------------------------------------------------
130 # Abort program with message:
132 # Prints program name and arguments to STDERR
133 # If --help is an option, prints message saying 'Try --help'
139 $name =~ s
|^.+[\\/]||; # Remove any directories from name
140 print STDERR
$name,": ",@_,"\n";
141 print STDERR
"Try `$name --help' for more information.\n"
142 if defined $options{"help"};
146 #---------------------------------------------------------------------
147 # Standard function for handling bad options:
149 # Prints an error message and exits.
151 # You can override this by setting $Getopt::Mixed::badOption to a
152 # function reference.
156 # The option that caused the error
157 # An optional string describing the problem
158 # Currently, this can be
159 # undef The option was not recognized
160 # 'ambiguous' The option could match several long options
163 # The option has already been removed from @ARGV. To put it back,
165 # splice(@ARGV,$_[0],0,$_[1]);
167 # If your function returns, it should return whatever you want
168 # nextOption to return.
172 my ($index, $option, $problem) = @_;
174 $problem = 'unrecognized' unless $problem;
176 abortMsg
("$problem option `$option'");
179 #---------------------------------------------------------------------
180 # Make sure we have the proper argument for this option:
182 # You can override this by setting $Getopt::Mixed::checkArg to a
183 # function reference.
186 # $i: Position of argument in @ARGV
187 # $value: The text appended to the option (undef if no text)
188 # $option: The pretty name of the option (as the user typed it)
189 # $type: The type of the option
192 # The value of the option's argument
196 my ($i,$value,$option,$type) = @_;
198 abortMsg
("option `$option' does not take an argument")
199 if (not $type and defined $value);
202 # An argument is required for this option:
203 $value = splice(@ARGV,$i,1) unless defined $value;
204 abortMsg
("option `$option' requires an argument")
205 unless defined $value;
209 abortMsg
("option `$option' requires integer argument")
210 if (defined $value and $value !~ /$intRegexp/o);
212 elsif ($type =~ /f$/) {
213 abortMsg
("option `$option' requires numeric argument")
214 if (defined $value and $value !~ /$floatRegexp/o);
216 elsif ($type =~ /^[=:]/ and ref($checkType)) {
217 $value = &$checkType($i,$value,$option,$type);
220 $value = "" if not defined $value and $type =~ /^:/;
225 #---------------------------------------------------------------------
226 # Find a match for an incomplete long option:
229 # The option text to match
232 # The option that matched, or
233 # undef, if no option matched, or
234 # (undef, 'ambiguous'), if multiple options matched
240 $opt =~ s/-/[^-]*-/g;
243 my @matches = grep(/^$opt$/, keys %options);
245 return undef if $#matches < 0;
246 return $matches[0] if $#matches == 0;
249 $opt = $options{$opt} if $options{$opt} =~ /^[^=:]/;
252 return (undef, 'ambiguous')
253 unless $_ eq $opt or $options{$_} eq $opt;
259 #---------------------------------------------------------------------
260 # Return the next option:
262 # Returns a list of 3 elements: (OPTION, VALUE, PRETTYNAME), where
263 # OPTION is the name of the option,
264 # VALUE is its argument, and
265 # PRETTYNAME is the option as the user entered it.
266 # Returns the null list if there are no more options to process
268 # If $order is $RETURN_IN_ORDER, and this is a normal argument (not an
269 # option), OPTION will be the null string, VALUE will be the argument,
270 # and PRETTYNAME will be undefined.
274 return () if $#ARGV < 0; # No more arguments
277 # We aren't processing any more options:
278 return ("", shift @ARGV) if $order == $RETURN_IN_ORDER;
282 # Find the next option:
284 while (length($ARGV[$i]) < 2 or
285 index($optionStart,substr($ARGV[$i],0,1)) < 0) {
286 return () if $order == $REQUIRE_ORDER;
287 return ("", shift @ARGV) if $order == $RETURN_IN_ORDER;
289 return () if $i > $#ARGV;
292 # Process the option:
293 my($option,$opt,$value,$optType,$prettyOpt);
295 if (substr($option,0,1) eq substr($option,1,1)) {
296 # If the option start character is repeated, it's a long option:
298 if (length($option) == 2) {
299 # A double dash by itself marks the end of the options:
300 $optionEnd = 1; # Don't process any more options
302 } # end if bare double dash
303 $opt = substr($option,2);
304 if ($opt =~ /^([^=]+)=(.*)$/) {
307 } # end if option is followed by value
308 $opt =~ tr/A-Z/a-z/ if $ignoreCase;
309 $prettyOpt = substr($option,0,2) . $opt;
311 ($opt, $problem) = findMatch
($opt)
312 unless defined $options{$opt} and length($opt) > 1;
313 return &$badOption($i,$option,$problem) unless $opt;
314 $optType = $options{$opt};
315 if ($optType =~ /^[^:=]/) {
317 $optType = $options{$opt};
319 $value = &$checkArg($i,$value,$prettyOpt,$optType);
320 } # end if long option
322 # It's a short option:
323 $opt = substr($option,1,1);
324 $opt =~ tr/A-Z/a-z/ if $ignoreCase;
325 return &$badOption($i,$option) unless defined $options{$opt};
326 $optType = $options{$opt};
327 if ($optType =~ /^[^:=]/) {
329 $optType = $options{$opt};
331 if (length($option) == 2 or $optType) {
332 # This is the last option in the group, so remove the group:
335 # Just remove this option from the group:
336 substr($ARGV[$i],1,1) = "";
339 $value = (length($option) > 2) ? substr($option,2) : undef;
340 $value =~ s/^=// if $value; # Allow either -d3 or -d=3
341 } # end if option takes an argument
342 $prettyOpt = substr($option,0,2);
343 $value = &$checkArg($i,$value,$prettyOpt,$optType);
344 } # end else short option
345 ($opt,$value,$prettyOpt);
348 #---------------------------------------------------------------------
352 # The same as for init()
353 # If no parameters are supplied, init() is NOT called. This allows
354 # you to call init() yourself and then change the configuration
358 # Sets $opt_X for each `-X' option encountered.
360 # Note that if --apple is a synonym for -a, then --apple will cause
361 # $opt_a to be set, not $opt_apple.
365 &init
if $#_ >= 0; # Pass arguments (if any) on to init
367 # If you want to use $RETURN_IN_ORDER, you have to call
368 # nextOption yourself; getOptions doesn't support it:
369 $order = $PERMUTE if $order == $RETURN_IN_ORDER;
371 my ($option,$value,$package);
373 $package = (caller)[0];
375 while (($option, $value) = nextOption
()) {
376 $option =~ s/\W/_/g; # Make a legal Perl identifier
377 $value = 1 unless defined $value;
378 eval("\$" . $package . '::opt_' . $option . ' = $value;');
384 #=====================================================================
385 # Package return value:
393 Getopt::Mixed - getopt processing with both long and short options
398 Getopt::Mixed::getOptions(...option-descriptions...);
399 ...examine $opt_* variables...
403 use Getopt::Mixed "nextOption";
404 Getopt::Mixed::init(...option-descriptions...);
405 while (($option, $value) = nextOption()) {
408 Getopt::Mixed::cleanup();
412 This package is my response to the standard modules Getopt::Std and
413 Getopt::Long. C<Std> doesn't support long options, and C<Long>
414 doesn't support short options. I wanted both, since long options are
415 easier to remember and short options are faster to type.
417 This package is intended to be the "Getopt-to-end-all-Getop's". It
418 combines (I hope) flexibility and simplicity. It supports both short
419 options (introduced by C<->) and long options (introduced by C<-->).
420 Short options which do not take an argument can be grouped together.
421 Short options which do take an argument must be the last option in
422 their group, because everything following the option will be
423 considered to be its argument.
425 There are two methods for using Getopt::Mixed: the simple method and
426 the flexible method. Both methods use the same format for option
429 =head2 Option Descriptions
431 The option-description arguments required by C<init> and C<getOptions>
432 are strings composed of individual option descriptions. Several
433 option descriptions can appear in the same string if they are
434 separated by whitespace.
436 Each description consists of the option name and an optional trailing
437 argument specifier. Option names may consist of any characters but
438 whitespace, C<=>, C<:>, and C<E<gt>>.
440 Values for argument specifiers are:
442 <none> option does not take an argument
443 =s :s option takes a mandatory (=) or optional (:) string argument
444 =i :i option takes a mandatory (=) or optional (:) integer argument
445 =f :f option takes a mandatory (=) or optional (:) real number argument
446 >new option is a synonym for option `new'
448 The C<E<gt>> specifier is not really an argument specifier. It
449 defines an option as being a synonym for another option. For example,
450 "a=i apples>a" would define B<-a> as an option that requires an
451 integer argument and B<--apples> as a synonym for B<-a>. Only one
452 level of synonyms is supported, and the root option must be listed
453 first. For example, "apples>a a=i" and "a=i apples>a oranges>apples"
454 are illegal; use "a=i apples>a oranges>a" if that's what you want.
456 For example, in the option description:
457 "a b=i c:s apple baker>b charlie:s"
458 -a and --apple do not take arguments
459 -b takes a mandatory integer argument
460 --baker is a synonym for -b
461 -c and --charlie take an optional string argument
463 If the first argument to C<init> or C<getOptions> is entirely
464 non-alphanumeric characters with no whitespace, it represents the
465 characters which can begin options.
467 =head2 User Interface
469 From the user's perspective, short options are introduced by a dash
470 (C<->) and long options are introduced by a double dash (C<-->).
471 Short options may be combined ("-a -b" can be written "-ab"), but an
472 option that takes an argument must be the last one in its group,
473 because anything following it is considered part of the argument. A
474 double dash by itself marks the end of the options; all arguments
475 following it are treated as normal arguments, not options. A single
476 dash by itself is treated as a normal argument, I<not> an option.
478 Long options may be abbreviated. An option B<--all-the-time> could be
479 abbreviated B<--all>, B<--a--tim>, or even B<--a>. Note that B<--time>
480 would not work; the abbreviation must start at the beginning of the
481 option name. If an abbreviation is ambiguous, an error message will
484 In the following examples, B<-i> and B<--int> take integer arguments,
485 B<-f> and B<--float> take floating point arguments, and B<-s> and
486 B<--string> take string arguments. All other options do not take an
490 -i=24 --int=-27 -f=24.5 --float=0.27 -s=Hello --string=Hello
492 If the argument is required, it can also be separated by whitespace:
494 -i 24 --int -27 -f 24.5 --float 0.27 -s Hello --string Hello
496 Note that if the option is followed by C<=>, whatever follows the C<=>
497 I<is> the argument, even if it's the null string. In the example
499 -i= 24 -f= 24.5 -s= Hello
501 B<-i> and B<-f> will cause an error, because the null string is not a
502 number, but B<-s> is perfectly legal; its argument is the null string,
505 Remember that optional arguments I<cannot> be separated from the
506 option by whitespace.
508 =head2 The Simple Method
513 Getopt::Mixed::getOptions(...option-descriptions...);
515 You then examine the C<$opt_*> variables to find out what options were
516 specified and the C<@ARGV> array to see what arguments are left.
518 If B<-a> is an option that doesn't take an argument, then C<$opt_a>
519 will be set to 1 if the option is present, or left undefined if the
520 option is not present.
522 If B<-b> is an option that takes an argument, then C<$opt_b> will be
523 set to the value of the argument if the option is present, or left
524 undefined if the option is not present. If the argument is optional
525 but not supplied, C<$opt_b> will be set to the null string.
527 Note that even if you specify that an option I<requires> a string
528 argument, you can still get the null string (if the user specifically
529 enters it). If the option requires a numeric argument, you will never
530 get the null string (because it isn't a number).
532 When converting the option name to a Perl identifier, any non-word
533 characters in the name will be converted to underscores (C<_>).
535 If the same option occurs more than once, only the last occurrence
536 will be recorded. If that's not acceptable, you'll have to use the
537 flexible method instead.
539 =head2 The Flexible Method
541 The flexible method is
543 use Getopt::Mixed "nextOption";
544 Getopt::Mixed::init(...option-descriptions...);
545 while (($option, $value, $pretty) = nextOption()) {
548 Getopt::Mixed::cleanup();
550 This lets you process arguments one at a time. You can then handle
551 repeated options any way you want to. It also lets you see option
552 names with non-alphanumeric characters without any translation. This
553 is also the only method that lets you find out what order the options
554 and other arguments were in.
556 First, you call Getopt::Mixed::init with the option descriptions.
557 Then, you keep calling nextOption until it returns an empty list.
558 Finally, you call Getopt::Mixed::cleanup when you're done. The
559 remaining (non-option) arguments will be found in @ARGV.
561 Each call to nextOption returns a list of the next option, its value,
562 and the option as the user typed it. The value will be undefined if
563 the option does not take an argument. The option is stripped of its
564 starter (e.g., you get "a" and "foo", not "-a" or "--foo"). If you
565 want to print an error message, use the third element, which does
566 include the option starter.
568 =head1 OTHER FUNCTIONS
570 Getopt::Mixed provides one other function you can use. C<abortMsg>
571 prints its arguments on STDERR, plus your program's name and a
572 newline. It then exits with status 1. For example, if F<foo.pl>
573 calls C<abortMsg> like this:
575 Getopt::Mixed::abortMsg("Error");
583 There are several customization variables you can set. All of these
584 variables should be set I<after> calling Getopt::Mixed::init and
585 I<before> calling nextOption.
587 If you set any of these variables, you I<must> check the version
588 number first. The easiest way to do this is like this:
590 use Getopt::Mixed 1.006;
592 If you are using the simple method, and you want to set these
593 variables, you'll need to call init before calling getOptions, like
596 use Getopt::Mixed 1.006;
597 Getopt::Mixed::init(...option-descriptions...);
598 ...set configuration variables...
599 Getopt::Mixed::getOptions(); # IMPORTANT: no parameters
605 $order can be set to $REQUIRE_ORDER, $PERMUTE, or $RETURN_IN_ORDER.
606 The default is $REQUIRE_ORDER if the environment variable
607 POSIXLY_CORRECT has been set, $PERMUTE otherwise.
609 $REQUIRE_ORDER means that no options can follow the first argument
610 which isn't an option.
612 $PERMUTE means that all options are treated as if they preceded all
615 $RETURN_IN_ORDER means that all arguments maintain their ordering.
616 When nextOption is called, and the next argument is not an option, it
617 returns the null string as the option and the argument as the value.
618 nextOption never returns the null list until all the arguments have
623 Ignore case when matching options. Default is 1 unless the option
624 descriptions contain an upper-case letter.
628 A string of characters that can start options. Default is "-".
632 A reference to a function that is called when an unrecognized option
633 is encountered. The function receives three arguments. $_[0] is the
634 position in @ARGV where the option came from. $_[1] is the option as
635 the user typed it (including the option start character). $_[2] is
636 either undef or a string describing the reason the option was not
637 recognized (Currently, the only possible value is 'ambiguous', for a
638 long option with several possible matches). The option has already
639 been removed from @ARGV. To put it back, you can say:
641 splice(@ARGV,$_[0],0,$_[1]);
643 The function can do anything you want to @ARGV. It should return
644 whatever you want nextOption to return.
646 The default is a function that prints an error message and exits the
651 A reference to a function that is called to make sure the argument
652 type is correct. The function receives four arguments. $_[0] is the
653 position in @ARGV where the option came from. $_[1] is the text
654 following the option, or undefined if there was no text following the
655 option. $_[2] is the name of the option as the user typed it
656 (including the option start character), suitable for error messages.
657 $_[3] is the argument type specifier.
659 The function can do anything you want to @ARGV. It should return
660 the value for this option.
662 The default is a function that prints an error message and exits the
663 program if the argument is not the right type for the option. You can
664 also adjust the behavior of the default function by changing
665 $intRegexp or $floatRegexp.
669 A regular expression that matches an integer. Default is
670 '^[-+]?\d+$', which matches a string of digits preceded by an
671 optional sign. Unlike the other configuration variables, this cannot
672 be changed after nextOption is called, because the pattern is compiled
677 A regular expression that matches a floating point number. Default is
678 '^[-+]?(\d*\.?\d+|\d+\.)$', which matches the following formats:
679 "123", "123.", "123.45", and ".123" (plus an optional sign). It does
680 not match exponential notation. Unlike the other configuration
681 variables, this cannot be changed after nextOption is called, because
682 the pattern is compiled only once.
686 A string of the characters which are legal argument types. The
687 default is 'sif', for String, Integer, and Floating point arguments.
688 The string should consist only of letters. Upper case letters are
689 discouraged, since this will hamper the case-folding of options. If
690 you change this, you should set $checkType to a function that will
691 check arguments of your new type. Unlike the other configuration
692 variables, this must be set I<before> calling init(), and cannot be
697 If you add new types to $typeChars, you should set this to a function
698 which will check arguments of the new types.
708 This document should be expanded.
712 A long option must be at least two characters long. Sorry.
716 The C<!> argument specifier of Getopt::Long is not supported, but you
717 could have options B<--foo> and B<--nofoo> and then do something like:
719 $opt_foo = 0 if $opt_nofoo;
723 The C<@> argument specifier of Getopt::Long is not supported. If you
724 want your values pushed into an array, you'll have to use nextOption
731 Getopt::Mixed is distributed under the terms of the GNU General Public
732 License as published by the Free Software Foundation; either version
733 2, or (at your option) any later version.
735 This means it is distributed in the hope that it will be useful, but
736 I<without any warranty>; without even the implied warranty of
737 I<merchantability> or I<fitness for a particular purpose>. See the
738 GNU General Public License for more details.
740 Since Perl scripts are only compiled at runtime, and simply calling
741 Getopt::Mixed does I<not> bring your program under the GPL, the only
742 real restriction is that you can't use Getopt::Mixed in an
743 binary-only distribution produced with C<dump> (unless you also
744 provide source code).
748 Christopher J. Madsen E<lt>F<ac608@yfn.ysu.edu>E<gt>
750 Thanks are also due to Andreas Koenig for helping Getopt::Mixed
751 conform to the standards for Perl modules and for answering a bunch of
752 questions. Any remaining deficiencies are my fault.