【问题标题】:Passing arrays to getopt in Perl在 Perl 中将数组传递给 getopt
【发布时间】:2019-09-26 22:27:10
【问题描述】:

我正在尝试在命令行中将数组传递给 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 将传递到数组?

【问题讨论】:

    标签: perl getopt-long


    【解决方案1】:

    使用s{,} 而不是s@。这个选项在perldoc Getopt::Long,段落Options with multiple values中描述:

    选项可以一次取多个值,例如

        --coordinates 52.2 16.4 --rgbcolor 255 255 149
    

    这可以通过在选项中添加重复说明符来实现 规格。重复说明符与 {...} 重复非常相似 可与正则表达式模式一起使用的说明符。为了 例如,上面的命令行将按如下方式处理:

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

    选项的目标必须是数组或数组引用。

    也可以指定最小和最大数量 一个选项的参数。 foo=s{2,4} 表示一个选项 至少两个,最多四个参数。 foo=s{1,} 表示一个或多个 价值观; foo:s{,} 表示零个或多个选项值。

    更准确地说,使用:

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

    在你的代码中就可以了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-01
      • 2011-11-06
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      • 2014-11-10
      • 1970-01-01
      相关资源
      最近更新 更多