Multi-value command line arguments

I am making a perl script and I need to get some values ​​from the command line. Example:

perl script.pl --arg1 op1 op2 op3 

I am using Getopt :: Long and I can get this to work:

 perl script.pl --arg1 op1 --arg1 op2 --arg1 op3 

But I really need (want) the first option.

I checked in my documentation and this should do what I want:

 GetOptions('arg1=s{3}' => \@myArray); 

http://search.cpan.org/~jv/Getopt-Long-2.38/lib/Getopt/Long.pm#Options_with_multiple_values

But I get this error:

Error in spec option: "arg1 = f {3}"

Any ideas / solutions?

+4
source share
4 answers

Your code works for me, but it looks like this feature has only been added to Getopt :: Long recently (version 2.35), so you may have an older version of Getopt :: Long. Run

 perl -MGetopt::Long -le'print $Getopt::Long::VERSION;' 

to find out which version you have.

+4
source

I think your problem might be f{3} . f used for float arguments (real numbers). You should use the s qualifier if you have strings as arguments. Regarding the number of arguments, the documentation says:

You can also specify the minimum and maximum number of arguments that the option accepts. foo = s {2,4} indicates a parameter that takes at least two and no more than 4 arguments. foo = s {,} indicates one or more values; foo: s {,} indicates zero or more parameter values.

Consider his note from the documents and adapt to your needs.

+4
source

I am not sure why people did not offer this solution, but this post is so old that it may be too late to be useful.

There is no automatic way to do this that I found.

What you need to do is specify a few arguments and parse them inside the code:

 perl myscript.pl -m 'abc' 

and then separate the value of the -m argument inside the code and do whatever is required of it.

+2
source

A similar question , the getoptions perl multi value function does not work , I think ... In any case, it seems that just using "optlist=s" => \@list, works for me to save a duplicate / repeat in an array; this is my version:

 $ perl --version | grep This && perl -MGetopt::Long -le'print $Getopt::Long::VERSION;' This is perl, v5.10.1 (*) built for i686-linux-gnu-thread-multi 2.38 

Example ( test.pl ):

 #!/usr/bin/perl use strict; use warnings; use Getopt::Long; my $numone = 0; my $numtwo = 1; my @list=(); my $result; $result = GetOptions ( "numone=i" => \$numone, "numtwo=i" => \$numtwo, "optlist=s" => \@list, ); printf("result: %d;\n", $result); printf("numone: %d, numtwo %d, optlist:\n", $numone, $numtwo); foreach my $tmplist (@list) { printf(" entry: '%s'\n", $tmplist); } 

Test output:

 $ perl test.pl --numone 10 --numtwo 20 --optlist testing --optlist more --optlist options result: 1; numone: 10, numtwo 20, optlist: entry: 'testing' entry: 'more' entry: 'options' 
0
source

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


All Articles