7 getopt - Process single-character switches with switch clustering
9 getopts - Process single-character switches with switch clustering
15 getopt('oDI'); # -o, -D & -I take arg. Sets opt_* as a side effect.
16 getopt('oDI', \%opts); # -o, -D & -I take arg. Values in %opts
17 getopts('oif:'); # -o & -i are boolean flags, -f takes an argument
18 # Sets opt_* as a side effect.
19 getopts('oif:', \%opts); # options as above. Values in %opts
23 The getopt() functions processes single-character switches with switch
24 clustering. Pass one argument which is a string containing all switches
25 that take an argument. For each switch found, sets $opt_x (where x is the
26 switch name) to the value of the argument, or 1 if no argument. Switches
27 which take an argument don't care whether there is a space between the
28 switch and the argument.
30 Note that, if your code is running under the recommended C<use strict
31 'vars'> pragma, it may be helpful to declare these package variables
32 via C<use vars> perhaps something like this:
34 use vars qw/ $opt_foo $opt_bar /;
36 For those of you who don't like additional variables being created, getopt()
37 and getopts() will also accept a hash reference as an optional second argument.
38 Hash keys will be x (where x is the switch name) with key values the value of
39 the argument or 1 if no argument is specified.
44 @EXPORT = qw(getopt getopts);
46 # $RCSfile: getopt.pl,v $$Revision: 4.1 $$Date: 92/08/07 18:23:58 $
48 # Process single-character switches with switch clustering. Pass one argument
49 # which is a string containing all switches that take an argument. For each
50 # switch found, sets $opt_x (where x is the switch name) to the value of the
51 # argument, or 1 if no argument. Switches which take an argument don't care
52 # whether there is a space between the switch and the argument.
55 # getopt('oDI'); # -o, -D & -I take arg. Sets opt_* as a side effect.
58 local($argumentative, $hash) = @_;
59 local($_,$first,$rest);
62 while (@ARGV && ($_ = $ARGV[0]) =~ /^-(.)(.*)/) {
63 ($first,$rest) = ($1,$2);
64 if (index($argumentative,$first) >= 0) {
73 $$hash{$first} = $rest;
76 ${"opt_$first"} = $rest;
77 push( @EXPORT, "\$opt_$first" );
86 push( @EXPORT, "\$opt_$first" );
97 local $Exporter::ExportLevel = 1;
103 # getopts('a:bc'); # -a takes arg. -b & -c not. Sets opt_* as a
107 local($argumentative, $hash) = @_;
108 local(@args,$_,$first,$rest);
112 @args = split( / */, $argumentative );
113 while(@ARGV && ($_ = $ARGV[0]) =~ /^-(.)(.*)/) {
114 ($first,$rest) = ($1,$2);
115 $pos = index($argumentative,$first);
117 if(defined($args[$pos+1]) and ($args[$pos+1] eq ':')) {
120 ++$errs unless @ARGV;
121 $rest = shift(@ARGV);
124 $$hash{$first} = $rest;
127 ${"opt_$first"} = $rest;
128 push( @EXPORT, "\$opt_$first" );
137 push( @EXPORT, "\$opt_$first" );
148 print STDERR "Unknown option: $first\n";
159 local $Exporter::ExportLevel = 1;