【问题标题】:Perl: dereferencing an array is using scalar context?Perl:取消引用数组正在使用标量上下文?
【发布时间】:2012-08-24 11:23:04
【问题描述】:

我对 Perl 和取消引用有一个奇怪的问题。

我有一个包含数组值的 INI 文件,位于两个不同的部分,例如

[Common]
animals =<<EOT
dog
cat
EOT

[ACME]
animals =<<EOT
cayote
bird
EOT

我有一个子例程将 INI 文件读入 %INI 哈希并处理多行条目。

然后我使用$org 变量来确定我们是使用公共数组还是特定组织数组。

@array = @{$INI{$org}->{animals}} || @{$INI{Common}->{animals}};

'Common' 数组工作正常,即如果 $org 不是 'ACME',我会得到值(狗猫),但如果 $org 等于 'ACME'`,我会得到 2 的值吗?

有什么想法吗??

【问题讨论】:

    标签: perl dereference


    【解决方案1】:

    取消引用数组当然不是强制标量上下文。但是使用|| 是。因此,$val = $special_val || "the default"; 之类的东西可以正常工作,而您的示例却不行。

    因此,@array 将包含单个数字(第一个数组中的元素数),或者如果为 0,则包含第二个数组的元素。

    perlop perldoc 页面甚至专门列出了这个例子:

    In particular, this means that you shouldn't use this for selecting
    between two aggregates for assignment:
    
        @a = @b || @c;              # this is wrong
        @a = scalar(@b) || @c;      # really meant this
        @a = @b ? @b : @c;          # this works fine, though
    

    根据您的需要,解决方案可能是:

    my @array = @{$INI{$org}->{animals}}
       ? @{$INI{$org}->{animals}}
       : @{$INI{Common}->{animals}};
    

    【讨论】:

    • 谢谢,当机立断,不要在我找到这个网站之前如何应对 :) .
    猜你喜欢
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 2012-05-01
    • 2018-02-25
    相关资源
    最近更新 更多