Getopt :: Long Pressing multiple values ​​in a hash option

Example:

use Getopt::Long;
%file ;
GetOptions('file=s%' =>
sub { push(@{$file{$_[1]}}, $_[2]) });

use Data::Dumper ;
print Dumper %file ;


print  @{$file{filename}} ;

my @file_array = @{$file_ref};

print "==\n @file_array == ";

I can execute and work:

 perl multipls.pl  --file filename=a.txt  --file  filename=b.txt filename=c.txt

I'm looking for

 perl multipls.pl  --file filename=a.txt  filename=b.txt filename=c.txt

How to achieve this?

+3
source share
3 answers

I don’t know how to convince Getopt::Longto do exactly what you ask, but I often use shell quotation to group several elements into one line, and then split the line into an array:

use strict;
use warnings;
use Data::Dumper;
use Getopt::Long;

my @files;
my $filelist;
GetOptions('file=s' => \$filelist);

if ($filelist) {
    $filelist =~ s/^\s+//; # Remove any leading whitespace
    @files = split /\s+/, $filelist;
}
print Dumper(\@files);

__END__


perl multipls.pl --file "filename=a.txt filename=b.txt"

$VAR1 = [
          'filename=a.txt',
          'filename=b.txt'
        ];
+2
source
use strict;
use warnings;
use Getopt::Long;

my @files;

GetOptions ( "file=s{,}" => \@files );

Side note:

An example in a problem does not really make sense. If all file names are transferred to the "filename" key, does it make sense to have a hash?

+2
source

use warnings; . , , :

%file;

,

my %file;

, , . use warnings;.

0

Source: https://habr.com/ru/post/1770304/


All Articles