2
    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.

toolic
  • 57,801
  • 17
  • 75
  • 117
Cool Camel
  • 57
  • 6

1 Answers1

3

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
Shawn
  • 47,241
  • 3
  • 26
  • 60
  • Instead of $gOptions{"filename"}->@* can you suggest a simpler option to just print 0th index of this array ? – Cool Camel Nov 22 '22 at 11:30
  • @CoolCamel See [perlreftut](https://perldoc.perl.org/perlreftut) for a start if you don't know how to work with arrayrefs (In particular, **Use Rule 2**). Considering how vital references are to any but the most trivial of data structures in perl, you'll need to get comfortable with them. – Shawn Nov 22 '22 at 11:31
  • I tried using $gOptions{"filename"}->[0] but it is not working – Cool Camel Nov 22 '22 at 11:34
  • That's the correct syntax and would be "a" in my example. What does *not working* mean? – Shawn Nov 22 '22 at 11:35
  • i am getting an error that using uninitialized value of $gOptions{"filename"}->[0] which means it is not able to parse it correctly in this way. – Cool Camel Nov 22 '22 at 11:38
  • oh I am sorry, I used double quotes for filename=s@{2} and forgot to give \ before @ – Cool Camel Nov 22 '22 at 11:40
  • Ah, yeah. Needs single quotes or an escape to avoid interpolation. – Shawn Nov 22 '22 at 11:40
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/249808/discussion-between-cool-camel-and-shawn). – Cool Camel Nov 22 '22 at 11:40
  • Thanks Shawn for helping, finding the right reference is the most difficult part ! :) – Cool Camel Nov 22 '22 at 11:41