Friday, May 20, 2011

Storing Options with Multiple Values in a Hash using Getopt::Long

I'm relatively new to Perl and was writing a program that takes long options on the command line. I quickly found the Getopt::Long module and started out getting options where each option's value was stored in a separate variable. One of the options has multiple values, e.g. --option5 0 1 2.

When I started, I had something like:

my ($option1, $option2, $option3, $option4, @option5);
my $result = GetOptions('option1=s'    => \$option1,
                        'option2=i'    => \$option2,
                        'option3=s'    => \$option3,
                        'option4=s'    => \$option4,
                        'option5=i{,}' => \@option5);

I wanted to change it to store the options in a hash since I had several options but got confused with the option that takes multiple values using a repeat specifier. The reason was stated in the documentation that "The destination for the option must be an array or array reference." What I didn't realize is that I needed to use this syntax "Alternatively, you can specify that the option can have multiple values by adding a "@", and pass a scalar reference as the destination" since my destination was now an uninitialized hash entry.

I ended up with this:

my %options;
my $result = GetOptions(\%options, 'option1=s',
                                   'option2=i',
                                   'option3=s',
                                   'option4=s',
                                   'option5=i@{,}');