I'm attempting to write a parser that will accept whitespace as a split, but am failing:
#!/usr/bin/env perl
use 5.036;
use warnings FATAL => 'all';
use autodie ':all';
use Getopt::ArgParse;
my $parser = Getopt::ArgParse->new_parser(
help => 'help menu',
);
$parser-> add_args(
['-foo', '-f', required => 1, type => 'Array', split => ' '],
#the above list gets output
#in: perl Getopt_ArgParse.pl -f a b c
#out: a
);
my $ns = $parser->parse_args(@ARGV);
say join ("\n", @{ $ns->foo });
However, when I run
perl Getopt_ArgParse.pl -f a b c
all I get is a
How can I write the script so that when I run perl Getopt_ArgParse.pl -f a b c
to get 3 values for -f
?
CodePudding user response:
There is no space in any of the arguments. (You are passing @ARGV = ( "-f", "a", "b", "c" );
.) That suggests split => ' '
is completely wrong for what you want to achieve.
So what would allow you to use that syntax? While Getopt::Long supports this syntax, I don't see anything in Getopt::ArgParse's documentation supporting it. Note that the lack of support of this syntax by Getopt::ArgParse might be intentional. -f a b c
usually means -f a -- b c
, so it's confusing, and one might accidentally use -f a b c
thinking it means -f a -- b c
.
So what syntax can you use instead? You can use -f a -f b -f c
or -f 'a b c'
. The latter requires split => ' '
in addition to type => 'Array'
, while the former works with or without it.
use v5.36;
use Getopt::ArgParse qw( );
my $parser = Getopt::ArgParse->new_parser();
$parser->add_args(
[ '--foo', '-f', type => 'Array', split => ' ' ],
[ '--bar', '-b', type => 'Array' ],
[ 'pos', nargs => '*' ],
);
my $ns = $parser->parse_args( @ARGV );
say for $ns->foo->@*;
say "--";
say for $ns->bar->@*;
say "--";
say for $ns->pos->@*;
$ perl a.pl -f a b c
a
--
--
b
c
$ perl a.pl -f a -f b -f c
a
b
c
--
--
$ perl a.pl -f 'a b c'
a
b
c
--
--
$ perl a.pl -b a -b b -b c
--
a
b
c
--
$ perl a.pl -b 'a b c'
--
a b c
--