Search code examples
perlgetopt-long

Passing arrays to getopt in Perl


I am attempting to pass an array to Perl at the command line.

I am reading instructions from https://perldoc.perl.org/Getopt/Long.html

my script is

#!/usr/bin/env perl

use strict;
use warnings FATAL => 'all';
use feature 'say';
use autodie ':all';
use Getopt::Long 'GetOptions';

my @array;
GetOptions ("a=s@" => \@array);#'file' indicates string on command line, '=s' means it must be a string
if (defined $array[0]) {#http://perldoc.perl.org/Getopt/Long.html#Options-with-values
    my @z = split(/,/,join(',',@array));
    say 'The array is ' . join (', ', @z);
}

which using the command line outputs

con@VB:~/Scripts$ perl array_getopt.pl -a v c d
The array is v

which is not correct, as it misses c and d

I have also tried GetOptions ("a=s" => \@array); which has the same error.

I see something on that page that says I would have to repeat the same tag over and over like perl array_getopt.pl -a v -a c -a d, which the end user won't like.

How can I pass information to the command line so -a v c d will pass to an array?


Solution

  • Use s{,} rather than s@. This options is described in perldoc Getopt::Long, paragraph Options with multiple values:

    Options can take multiple values at once, for example

        --coordinates 52.2 16.4 --rgbcolor 255 255 149
    

    This can be accomplished by adding a repeat specifier to the option specification. Repeat specifiers are very similar to the {...} repeat specifiers that can be used with regular expression patterns. For example, the above command line would be handled as follows:

        GetOptions('coordinates=f{2}' => \@coor, 'rgbcolor=i{3}' => \@color);
    

    The destination for the option must be an array or array reference.

    It is also possible to specify the minimal and maximal number of arguments an option takes. foo=s{2,4} indicates an option that takes at least two and at most 4 arguments. foo=s{1,} indicates one or more values; foo:s{,} indicates zero or more option values.

    More precisely, using:

    GetOptions ("a=s{,}" => \@array);
    

    in your code does the trick.