Perl Getopt


What are the capabilities of Getopt::Long?

Getopt::Long supports:

  • boolean switches
  • incremental switches
  • options with single value
  • options with multiple values
  • options with hash values.

Basic examples:

use strict;
use Getopt::Long;
my $data = "file.dat";
my $length = 24;
my $verbose;
    "length=i" => \$length, # numeric
    "file=s" => \$data, # string
    "verbose" => \$verbose # boolean flag

What is an option specifier?

use strict;
use Getopt::Long;
my $name;
GetOptions('name=s@{1,}' => \$name);

In the above code, the first parameter to GetOptions ** name=s@{1,}** is the option specifier. The part that comes before the equal sign is the name of the option. The part that comes after the equal sign specify other information. See below.

What are the four components of an option specifier?

  1. the name of the option
  2. the data type (boolean, string, integer, etc)
  3. whether to expect a single value, a list, or a hash
  4. the minimum and maximum number of values to accept.

How to specify that an option should be an integer?


How to specify that an option should be a string?


How to specify a boolean option?

name!    // Presence of --name with set $name to 1, --noname will set $name to 0
name+    // Increment the variable each time the option is found
        // If $name is 0, then --name --name --name will set $name to 3

The present of —name on the command line will set the corresponding variable to one.

How to specify an option that expects an array of string, with minimum of one element, and no upper bound?


Now invoke the script as:

myscript --name Barbie Brian Steve

will set $name to the array reference ['Barbie', 'Brian', 'Steve'].

How to specify that an option should expect a hash value?

Giving a hash value to an option is very similar. Replace @ with % and on the command line give arguments as key=value pairs:

my $name;
GetOptions('name=s%{1,}', \$name);

and run the script as:

myscript --name Barbie=Director JJ=Member

This will store the hash reference {Barbie => 'Director', JJ => 'Member'} in $name.

How to store all options into a hash?

By passing a hash reference as the first argument to GetOptions, you can store the complete set of option values in a hash.

my $options = {};
GetOptions($options, 'name=s', 'verbose');

How can I learn more about Getopt::Long?

perldoc Getopt::Long
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License