Saturday 2 June 2007

getopt revisited

Well been tidying some scripts that will generate a list of mp3s and modify them as need be so that that they are wooshy-friendly. As much as you should write modules, there's nothing like getting a quick 10-line script that uses a module.

Anyhow perl's getopt modules have got a little complicated over time. i.e. there are 7 or 8 of them available and they can get confusing. Namely, can mix up getopt::std and getopt::simple quite easily. The fact that getopt::simple is actually a wrapper for getopt::long makes it worse. So in actual fact getopt::simple is not all that simple at all.

I would use getopt::std if you want something quickly done with some options albeit in the form of one dash / one letter. Something a bit more complicated go for getopt::long. Forget the rest...

Links:

Google Keywords: perl, getopt, getopts

Sample Perl Code:
#!/usr/bin/perl

# The Std version of Getopt allows for the processing of single
# character switches
use Getopt::Std;

# The hash %options is initialized and will store the switch as
# the key and the switch argument as the value
my %options=();

# the "\" is simply a pointer to the %options hash
# "a" is treated like a flag while "b" needs an argument after
# the switch is called indicated by the ":"
getopts("ab:",\%options);

# "defined" is a perl function that will return a boolean depending
# on if the variable in question has been previously defined
if (defined $options{a}) {
print "You have selected the option -a and its value is \"$options{a}\"\n";
}

# This if statement will return the same thing as the above example
# using the perl function "defined"
if ($options{b}) {
print "You have selected the option -b and its value is \"$options{b}\"\n";
}