在 Perl 中将数组传递给 getopt

Passing arrays to getopt in Perl

我正在尝试通过命令行将数组传递给 Perl。

我正在阅读来自 https://perldoc.perl.org/Getopt/Long.html

的说明

我的剧本是

#!/usr/bin/env perl

use strict;
use warnings FATAL => 'all';
use feature 'say';
use autodie ':all';
use Getopt::Long 'GetOptions';

my @array;
GetOptions ("a=s@" => \@array);#'file' indicates string on command line, '=s' means it must be a string
if (defined $array[0]) {#http://perldoc.perl.org/Getopt/Long.html#Options-with-values
    my @z = split(/,/,join(',',@array));
    say 'The array is ' . join (', ', @z);
}

使用命令行输出

con@VB:~/Scripts$ perl array_getopt.pl -a v c d
The array is v

这是不正确的,因为它遗漏了 cd

我也试过了 GetOptions ("a=s" => \@array); 有同样的错误。

我在那个页面上看到一些东西,说我必须像 perl array_getopt.pl -a v -a c -a d 一样一遍又一遍地重复相同的标签,最终用户不会喜欢。

如何将信息传递到命令行以便 -a v c d 传递到数组?

使用 s{,} 而不是 s@perldoc Getopt::LongOptions with multiple values:

中描述了此选项

Options can take multiple values at once, for example

    --coordinates 52.2 16.4 --rgbcolor 255 255 149

This can be accomplished by adding a repeat specifier to the option specification. Repeat specifiers are very similar to the {...} repeat specifiers that can be used with regular expression patterns. For example, the above command line would be handled as follows:

    GetOptions('coordinates=f{2}' => \@coor, 'rgbcolor=i{3}' => \@color);

The destination for the option must be an array or array reference.

It is also possible to specify the minimal and maximal number of arguments an option takes. foo=s{2,4} indicates an option that takes at least two and at most 4 arguments. foo=s{1,} indicates one or more values; foo:s{,} indicates zero or more option values.

更准确地说,使用:

GetOptions ("a=s{,}" => \@array);

在您的代码中就可以了。