This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[inseparable changes from patch from perl5.003_12 to perl5.003_13]
[perl5.git] / lib / getopts.pl
CommitLineData
a687059c
LW
1;# getopts.pl - a better getopt.pl
2
3;# Usage:
4;# do Getopts('a:bc'); # -a takes arg. -b & -c not. Sets opt_* as a
5;# # side effect.
6
7sub Getopts {
8 local($argumentative) = @_;
55204971
LW
9 local(@args,$_,$first,$rest);
10 local($errs) = 0;
a687059c
LW
11
12 @args = split( / */, $argumentative );
55204971 13 while(@ARGV && ($_ = $ARGV[0]) =~ /^-(.)(.*)/) {
a687059c
LW
14 ($first,$rest) = ($1,$2);
15 $pos = index($argumentative,$first);
55497cff 16 if($pos >= 0) {
17 if($pos < $#args && $args[$pos+1] eq ':') {
bf38876a 18 shift(@ARGV);
a687059c 19 if($rest eq '') {
8adcabd8 20 ++$errs unless @ARGV;
bf38876a 21 $rest = shift(@ARGV);
a687059c 22 }
55497cff 23 ${"opt_$first"} = $rest;
a687059c
LW
24 }
25 else {
55497cff 26 ${"opt_$first"} = 1;
a687059c 27 if($rest eq '') {
bf38876a 28 shift(@ARGV);
a687059c
LW
29 }
30 else {
31 $ARGV[0] = "-$rest";
32 }
33 }
34 }
35 else {
ac58e20f
LW
36 print STDERR "Unknown option: $first\n";
37 ++$errs;
a687059c
LW
38 if($rest ne '') {
39 $ARGV[0] = "-$rest";
40 }
41 else {
bf38876a 42 shift(@ARGV);
a687059c
LW
43 }
44 }
45 }
ac58e20f 46 $errs == 0;
a687059c
LW
47}
48
491;