Using options in Perl programs (with Getopt)

The utility getopt (or getopts) gets command line parameters for your program. The bash and ksh shells come with getopt builtin; getopts is a separate program.

To use this capability from Perl, use the Getopt library: either Getopt::Std or Getopt::Long. Most of the time you’ll probably want to use Getopt::Long just for its flexibility.

To start using Getopt::Std, use something like this initial fragment:

use Getopt::Std;
%options=();
getopts("vs:i",\%options);

This will give you the options -v, -i, and -s arg. After this fragment executes, the associated hash table entries will be defined if the argument is present – and if it is present, the value will be either 1 or the argument given. For example, $options{v} might be set to 1, and $options{s} could be “arg”.

Using Getopt::Long isn’t much more difficult:

use Getopt::Long;
Getoptions("s" => \$sflag,
"verbose!" => \$verbose,
"file=s" => \$file,
"interval=i" => \$interval,
"auto:i" => \$auto)

This set of options shows most of the features of Getoptions(). The -verbose option is a toggle (as noted by the ‘!’ at the end of the option name), and the alternate can be specified as -noverbose. For the -file option, a string argument is required (specified by the ‘=s’ on the end of the option specification). The ‘=i’ (as exemplified by the -interval option) means that an integer argument is required, and the ‘:i’ for the -auto option means a integer argument is optional. Float values (real numbers) are also possible by using the ‘f’ flag (such as “real=f” – option -real requiring a float argument).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: