Perl:解除引用数组正在使用标量上下文?

and*_*l73 1 perl dereference

我对Perl和解除引用有一个奇怪的问题.

我有一个带有数组值的INI文件,在两个不同的部分下,例如

[Common]
animals =<<EOT
dog
cat
EOT

[ACME]
animals =<<EOT
cayote
bird
EOT
Run Code Online (Sandbox Code Playgroud)

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

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

@array = @{$INI{$org}->{animals}} || @{$INI{Common}->{animals}};
Run Code Online (Sandbox Code Playgroud)

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

有任何想法吗??

Mor*_*kus 6

Derefencing数组当然不会强制标量上下文.但使用||是.因此,$val = $special_val || "the default";工作得很好,而你的例子没有.

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

perlopperldoc页也甚至speficially列出了这个例子:

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
Run Code Online (Sandbox Code Playgroud)

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

my @array = @{$INI{$org}->{animals}}
   ? @{$INI{$org}->{animals}}
   : @{$INI{Common}->{animals}};
Run Code Online (Sandbox Code Playgroud)