Actions: | Security

Navigation: Home | Services | Tools | Articles | Other

Quick Hints for the Getopt::Long perl module

Getopt::Long is a valuable perl module that provides functionality for processing command line options.

The pod for Getopt::Long is helpful, but I want a handy reference for some usages that I forget.

Option variants


This allows --foo to negated with --nofoo:

GetOptions('foo!' => \$foo);

This allows an option to contain a scalar and for the value to be incremented each time the option appears on the command line:

GetOptions('foo+' => \$foo);
Options with values

Options can be specified that take values which may be integer numbers, floating point numbers or strings (i, f, s, respectively). Options that require values are specified with =, options that may or may not take values are specified with a colon:

GetOptions('foo:i' => \$foo,
           ' bar=f' => \$bar,
            'baz:s' => \$baz );

The above example specifies an option 'foo' that may be given an integer value, an option 'bar' that must be given a floating point value and an option 'baz' that may be given a string value. If no suitable value is supplied, string valued options get an empty string '' assigned, while numeric options are set to '0'. Here are some valid invocations:

--foo --bar 7.2 --baz bazvalue
--foo=7 --baz=bazvalue
Options with multiple values

Options can be specified to take multiple values by making the desination variable an array (or an arrayref).:

GetOptions('foo=i' => \@foos);
--foo 2 --foo 5

Allowing the multiple values to be given as a comma-separated list is usually a good idea.:

GetOptions ("foo=i" => \@foos);
@foos = split(/,/,join(',',@foos));

Default values

As usual in perl, TIMTOWTDI applies, but I sometimes use the following idiom for default values:

$options = GetOptions( ... );
$foo = defined($foo) ? $foo : 1;
$bar = defined($bar) ? $bar : 'default value for bar';

Other notes

Sometimes, it is convenient to have a hash as the option destination; I like this approach when building a module, because it makes it easier too pass the data around in its entirety.:

my %options;
if ($options{'help'}) { usage(); }
$options{'foo'} = defined($options{'foo'} ? $options{'foo'} : 'default value for foo';

If you want to use the above style AND have multiple values for an option, it will be need to be specified using an alternative syntax:

@foos = split(/,/,join(',',@options{'foo'}));

As I have used above, but worth explicitly stating, these are both valid usages:

--foo foovalue

I gained some insight from the docs, some from the author, some from more on getopt and configuration and some from painful practice.