use Getopt::Long;
GetOptions(\%gOptions,
"help",
"size=i",
"filename=s{2}",
);
I am passing options like -
--size 200 --filename abc.txt def.txt
I tried accessing filename from the hash specification through
my @array = $gOptions{filename};
print $array[0];
print $array[1];
However, this is not working. How to access multiple option values from a hash specification %gOptions
?
Note :
I can map filename
to separate array like this -
"filename=s{2}" => \@filearray,
print "$filearray[1];"
but I am not preferring this method.
CodePudding user response:
The documentation on this form of usage says:
For options that take list or hash values, it is necessary to indicate this by appending an @ or % sign after the type
and it will then use a reference to an array or hash in the appropriate field to hold values.
So...
#!/usr/bin/env perl
use warnings;
use strict;
use feature qw/say/;
use Getopt::Long;
my %gOptions;
GetOptions(\%gOptions,
"help",
"size=i",
# The @ has to come after the type, and before the repeat count.
# Note the single quotes so @{2} isn't subject to variable interpolation
'filename=s@{2}',
);
say for $gOptions{"filename"}->@* if exists $gOptions{"filename"};
# or @{$gOptions{"filename"}} if your perl is too old for postderef syntax
Example:
$ perl foo.pl --filename a b
a
b