http://qs321.pair.com?node_id=886585


in reply to Re^2: GetOpts::long Multiple Parameters per option
in thread GetOpts::long Multiple Parameters per option

the only problem I have with this is defining parameters for %options before building %options with GetOptions If for instance I needed to have multiple pairs per flag ...
It still works if you handle it properly:
#!/usr/bin/perl use v5.10.1; use strict; use warnings; use Getopt::Long; my (@a, @b); my %options = ( 'a' => \@a, 'b' => \@b, ); GetOptions ( 'a=s{2}' => \@a, 'b=s{2}' => \@b, ); # say "$options{'a'}->[0], $options{'a'}->[1]"; # say "$options{'b'}->[0], $options{'b'}->[1]"; say "@{ $options{'a'} }"; say "@{ $options{'b'} }";

Firstly, don't dereference the array elements one at a time. Among other things, you get

Use of uninitialized value in concatenation (.) or string at ./pm-886582 line 20.
when there is no -b flag and args. But more important, you've hidden the fact that you really collected all of the arguments from all of the -a flags.

Now you will see that:

./pm-886582 -a a1_1 a1_2 -a a2_1 a2_2 -a a3_1 a3_2 a1_1 a1_2 a2_1 a2_2 a3_1 a3_2
(note that the output has an empty line where non-existent @{ $options{'b'} } is not printed.)

IOW, all of the -a pairs are gathered into your @{ $options{'a'} }. All you need now is some code to check that the array has an even number of elements and then to take it apart into (multiple) pairs.

Thanks for the assist.
My pleasure. One last word of caution. The docs mention that this is an experimental feature. I haven't had any problems with it so far, but YMMV.