Anyone who has tried to parse command-line options in Perl knows how messy the process gets with increasing number of options. Luckily, there are some modules that the whole process more manageable. The tutorials I am learning from are http://systhread.net/texts/200704optparse.php#one and http://aplawrence.com/Unix/perlgetopts.html.
Without using a special Perl module, options can be parsed as follows (credit to http://systhread.net/texts/200704optparse.php#one)
Without using a special Perl module, options can be parsed as follows (credit to http://systhread.net/texts/200704optparse.php#one)
while ( my $arg = shift @ARGV ) {
if ( $arg eq '-F' ) {
$F_FLAG = 1;
} elsif ( $arg eq '-f' ) {
$FILE_ARGUMENT = shift @ARGV;
} elsif ( $arg eq '-u' ) {
usage();
} else {
usage();
exit 1;
}
}
Ultimately, using the getopt
module should be done if it is available, why reinvent the wheel? Here is an example of using the Getopt
module:
use Getopt::Std;
...
getopt ('f:uF');
die "Usage: $0 [ -f filename -u ]\n"
unless ( $opt_f or $opt_u );
if ($opt_f) {
my $filename = shift @ARGV;
} elsif ($opt_u) {
usage();
exit 0;
}
Definitely shorter and compact.
A.P. Lawrence shows an even more succinct example which demonstrates the power of the getopts package.#!/usr/bin/perl
# script is "./g"
use Getopt::Std;
%options=();
getopts("o:d:fF",\%options);
# like the shell getopt, "o:" and "d:" means d and o take arguments
print "-o $options{o}\n" if defined $options{o};
print "-d $options{d}\n" if defined $options{d};
print "-f $options{f}\n" if defined $options{f};
print "-F $options{F}\n" if defined $options{F};
print "Unprocessed by Getopt::Std:\n" if $ARGV[0];
foreach (@ARGV) {
print "$_\n";
}
Well, this means we don't have to worry about the order in which the flags are entered. Plus, creating one-liners to check the validity of arguments seems simple.
Comments