in reply to GetOpts::long Multiple Parameters per option

Or:
my @a; my @b; GetOptions ( "a=s" => \@a, "b=s" => \@b ); @a = split(/,/,join(',',@a)); @b = split(/,/,join(',',@b)); if ( scalar(@a) !=2 || scalar(@b) !=2 ){ # shout at user here }
The command line in that case would look like either of these (both will work)
perl the_script -a 1 -a 2 -b 10 -b 30
or
perl the_script -a 1,2 -b 10,30
I think the requirement to either specify the option name along with a value or use comma-separation makes the command a little clearer to read. Personal preference really.

Replies are listed 'Best First'.
Re^2: GetOpts::long Multiple Parameters per option
by thargas (Deacon) on Feb 08, 2011 at 12:46 UTC
    Re:
    GetOptions ( "a=s" => \@a, "b=s" => \@b ); @a = split(/,/,join(',',@a)); @b = split(/,/,join(',',@b));

    You don't have to parse after the fact; you can have the reference in the GetOptions() call be a sub ref and mangle things there. E.G.

    my $opt = { # this has to be first because the sub-refs # below are closures using it. grot => [], }; my $splitter = sub { my ($name, $val) = @_; push @{$opt->{$name}}, split q{,}, $val; }; GetOptions( $opt, 'grot=s@' => $splitter, ) or die "can't parse options";

    It's not so much useful in this case, where there is only one use, but if you have several options which can have multiple comma-separated values, this piece of code can be handy. I've also used other sub-refs in GetOptions, e.g. if the option value specifies a file-name, but you want the option to end up containing the file contents, you might use something like:

    my $from_file = sub { my ($name, $val) = @_; open my $fh, "<$val" or die "can\'t open file \'$val\'"; local $/ = undef; $opt->{$name} = <$fh>; close($fh); };