Skip to main content

Parsing Commandline Options in Perl

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)

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

Popular posts from this blog

Distribution of Wealth in the US

The rich get richer and the poor get poorer. I heard this statement quite a bit lately particularly in light of the sub-prime mortgage and general housing crisis in the US. The country has enjoyed significant economic prosperity and both Clinton and Bush boasted economic growth under their reign. Unfortunately, the beneficiaries of the economic boom are not people from all economic backgrounds, but rather the top 10%. To make things worse, Bush gave tax cuts mainly targeting the top 10%. Being more of a numbers guy, I always wanted showing the validity of the-rich-get-richer-n-the-poor-get-poorer statement. Thanks to Wikipedia , I have finally found it!! Both the mean and median net worth of families for the bottom 50% of the population has remained absolutely flat while the 75th-90th percentile see a decent growth and the top 10% enjoy the most appreciation on their net worth. So, if you factor in inflation, the-rich-get-richer-n-the-poor-get-poorer probably holds true. The g...

Correlation Between Finger Length and Aggression/Success/Homosexuality

I came across an interesting article on BBC (Finger length 'key to aggression' ) today and The Economist has a similar article ( Neuroeconomics: Digitally enhanced ). They report a positive correlation between the length of mens' ring fingers and their success in high-stress securities trading. Actually, the more correct comparison s between the ratio of the ring to index finger and success/aggression. In women, the ring and index fingers are comparable, however the ring finger is significantly longer than the index finger in men. In this study, the researchers only looked at men's fingers. Apparently the level of testerone in a fetus is exposed to during pregnancy affects length of fingers as well as the level of aggression. More aggressive traders tend to have longer ring fingers and they happen to be more successful, after factoring out the effect of experience. They also reached a similar conclusion when looking at college students. Having a short ring finger...

Online Storage Solutions

Problem: I often need to have some files readily available online so that I can access them from any computer. There are many ways to go about solving this problem and each comes with its set of shortcomings: Yahoo! Briefcase - 30MB limit Online storage services like Box.net, Xdrive, MediaMax - usually cost money; signing up is cumbersome Email to myself as an attachment - enough said there It's time to find a home-made solution. The solution I am about to suggest is intended for -- A *NIX user someone with access to a *NIX web server Solution: I am a linux user and I have user level access to a web server. The web server is configured such that the public does not have access to directory structure. So, I would need to write a script that copies my files to the web server and creates an index listing my files. Password protection of the storage would follow after that. Client Side: Use the following script to transfer file to server, make the file readable by public and execu...