Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re^3: GetOpts::long Multiple Parameters per option

by broomduster (Priest)
on Feb 07, 2011 at 02:24 UTC ( #886585=note: print w/ replies, xml ) Need Help??


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.


Comment on Re^3: GetOpts::long Multiple Parameters per option
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://886585]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2014-10-25 02:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (140 votes), past polls