EyeOpener has asked for the wisdom of the Perl Monks concerning the following question:
I'm developing a small netadmin-type script. I don't intend this to have much of an audience beyond a few folks in my immediate group, but as these things tend to grow in ways unimaginable, I want to make it somewhat flexible. I'm playing around with Getopt::Std to allow for switches.
I'd like the script to handle 5 switches, all of which are optional:
-h = help
-i and -o = input and output filenames
-w and -s = numeric values
If any of the -iows switches are used, they must be accompanied by a valid argument (filename for -io, numeric for -ws). The &usage sub should be called if -h is used, or if any of the other switches are used incorrectly (i.e., with a missing or invalid argument).
Coding these rules is more difficult than I thought. My best attempt is this:
#!/usr/bin/perl -w use strict; use Getopt::Std; my %args; getopts('w:s:i:o:h', \%args); &usage() if @ARGV || $args{h} || (exists $args{w} && !defined $args{w} || $args{w} !~ /^\d*$/) || (exists $args{s} && !defined $args{s} || $args{s} !~ /^\d*$/) || (exists $args{i} && !defined $args{i} || $args{i} =~ /^-\w$/) || (exists $args{o} && !defined $args{o} || $args{o} =~ /^-\w$/) ;
This $args{i} =~ /^-\w$/ was added to catch the situation where the script was called with just "-i -o" as parameters. getopts saw the "-o" as a valid argument to the "-i" switch.
This is close, but there are a few things wrong. It doesn't complain about unknown options (-x); it produces "Use of uninitialized value in pattern match" warnings when switches aren't used (I'm picky); and worst of all, adding all these specific catchalls doesn't seem very Perlish.
Seems like a good time to Ask The Experts. Is there a simple way to accomplish this with Getopt::Std, or would I need to move to Getopt::Long or some other mod?
Thanks!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Using GetOpt::Std to parse switches with arguments
by Kanji (Parson) on Apr 19, 2002 at 21:27 UTC | |
by EyeOpener (Scribe) on Apr 19, 2002 at 21:40 UTC | |
|
Re: Using GetOpt::Std to parse switches with arguments
by snafu (Chaplain) on Apr 19, 2002 at 21:21 UTC | |
|
Re: Using GetOpt::Std to parse switches with arguments
by TheHobbit (Pilgrim) on Apr 19, 2002 at 21:14 UTC | |
|
Re: Using GetOpt::Std to parse switches with arguments
by rbc (Curate) on Apr 19, 2002 at 21:36 UTC |