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 For those of you who don't like additional variables being created, getopt()
31 and getopts() will also accept a hash reference as an optional second argument.
32 Hash keys will be x (where x is the switch name) with key values the value of
33 the argument or 1 if no argument is specified.
38 @EXPORT = qw(getopt getopts);
40 # $RCSfile: getopt.pl,v $$Revision: 4.1 $$Date: 92/08/07 18:23:58 $
42 # Process single-character switches with switch clustering. Pass one argument
43 # which is a string containing all switches that take an argument. For each
44 # switch found, sets $opt_x (where x is the switch name) to the value of the
45 # argument, or 1 if no argument. Switches which take an argument don't care
46 # whether there is a space between the switch and the argument.
49 # getopt('oDI'); # -o, -D & -I take arg. Sets opt_* as a side effect.
52 local($argumentative, $hash) = @_;
53 local($_,$first,$rest);
54 local $Exporter::ExportLevel;
56 while (@ARGV && ($_ = $ARGV[0]) =~ /^-(.)(.*)/) {
57 ($first,$rest) = ($1,$2);
58 if (index($argumentative,$first) >= 0) {
67 $$hash{$first} = $rest;
70 eval "\$opt_$first = \$rest;";
71 push( @EXPORT, "\$opt_$first" );
79 eval "\$opt_$first = 1;";
80 push( @EXPORT, "\$opt_$first" );
90 $Exporter::ExportLevel++;
95 # getopts('a:bc'); # -a takes arg. -b & -c not. Sets opt_* as a
99 local($argumentative, $hash) = @_;
100 local(@args,$_,$first,$rest);
102 local $Exporter::ExportLevel;
104 @args = split( / */, $argumentative );
105 while(@ARGV && ($_ = $ARGV[0]) =~ /^-(.)(.*)/) {
106 ($first,$rest) = ($1,$2);
107 $pos = index($argumentative,$first);
109 if(defined($args[$pos+1]) and ($args[$pos+1] eq ':')) {
112 ++$errs unless @ARGV;
113 $rest = shift(@ARGV);
116 $$hash{$first} = $rest;
119 eval "\$opt_$first = \$rest;";
120 push( @EXPORT, "\$opt_$first" );
128 eval "\$opt_$first = 1";
129 push( @EXPORT, "\$opt_$first" );
140 print STDERR "Unknown option: $first\n";
150 $Exporter::ExportLevel++;