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!
In reply to Using GetOpt::Std to parse switches with arguments by EyeOpener
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |