【问题标题】:How to access multiple option values from hash specification如何从哈希规范访问多个选项值
【发布时间】:2022-11-22 19:43:32
【问题描述】:
    use Getopt::Long;

    GetOptions(\%gOptions,
        "help",
        "size=i",
        "filename=s{2}",
    );

我正在传递选项,例如 -

--size 200 --filename abc.txt def.txt

我尝试通过哈希规范访问文件名

my @array = $gOptions{filename};
print $array[0];
print $array[1];

但是,这是行不通的。如何从哈希规范%gOptions访问多个选项值?

笔记 : 我可以像这样将 filename 映射到单独的数组 -

"filename=s{2}" => \@filearray,
print "$filearray[1];"

但我不喜欢这种方法。

【问题讨论】:

    标签: perl getopt-long


    【解决方案1】:

    documentation 关于这种用法的说法是:

    对于采用列表或散列值的选项,有必要通过在类型后附加 @ 或 % 符号来表明这一点

    然后它将在适当的字段中使用对数组或散列的引用来保存值。

    所以...

    #!/usr/bin/env perl
    use warnings;
    use strict;
    use feature qw/say/;
    use Getopt::Long;
    
    my %gOptions;
    
    GetOptions(%gOptions,
      "help",
      "size=i",
      # The @ has to come after the type, and before the repeat count.
      # Note the single quotes so @{2} isn't subject to variable interpolation
      'filename=s@{2}', 
    );
    
    say for $gOptions{"filename"}->@* if exists $gOptions{"filename"};
    # or @{$gOptions{"filename"}} if your perl is too old for postderef syntax
    

    例子:

    $ perl foo.pl --filename a b
    a
    b
    

    【讨论】:

    • 除了 $gOptions{"filename"}->@* 你能建议一个更简单的选项来只打印这个数组的第 0 个索引吗?
    • @CoolCamel 如果您不知道如何使用 arrayrefs(特别是,使用规则 2).考虑到对 perl 中除了最琐碎的数据结构以外的任何数据结构的引用都是多么重要,您需要熟悉它们。
    • 我尝试使用 $gOptions{"filename"}->[0] 但它不起作用
    • 这是正确的语法,在我的示例中是“a”。做什么不工作意思是?
    • 我收到一个错误,使用 $gOptions{"filename"}->[0] 的未初始化值,这意味着它无法以这种方式正确解析它。
    猜你喜欢
    • 1970-01-01
    • 2014-12-14
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-11
    • 2013-06-06
    • 2020-03-27
    相关资源
    最近更新 更多