Perl Getopt

Getopt::Long supports boolean switches, incremental switches, options with single value, options with multiple values, and even options with hash values.

name          // Presence of --name will set $name to 1
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
name=s        // String value is required
name=i        // Integer value is required

The option specifier consist of four components: the name of the option; the data type (boolean, string, integer, etc); whether to expect a single value, a list, or a hash; and the minimum and maximum number of values to accept.

name=s@{1,}   // This option expect an array of string, minimum of one element, and no upper bound
my $name;
GetOptions('name=s@{1,}' => \$name);

Now invoke the script as:

myscript --name Barbie Brian Steve

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

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);

Running the script as:

myscript --name Barbie=Director JJ=Member

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

Storing Options in 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');
page_revision: 0, last_edited: 1227282012|%e %b %Y, %H:%M %Z (%O ago)
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License