简体   繁体   English

Perl:使用标量上下文取消引用数组?

[英]Perl: dereferencing an array is using scalar context?

I have a strange issue with Perl and dereferencing. 我对Perl和取消引用有一个奇怪的问题。

I have an INI file with array values, under two different sections eg 我在两个不同的部分下都有一个带有数组值的INI文件,例如

[Common]
animals =<<EOT
dog
cat
EOT

[ACME]
animals =<<EOT
cayote
bird
EOT

I have a sub routine to read the INI file into an %INI hash and cope with multi-line entries. 我有一个子例程,可将INI文件读入%INI哈希并处理多行条目。

I then use an $org variable to determine whether we use the common array or a specific organisation array. 然后,我使用$org变量来确定我们使用公共数组还是特定组织数组。

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

The 'Common' array works fine, ie if $org is anything but 'ACME' I get the values (dog cat) but if $org equals 'ACME'` I get a value of 2 back? 'Common'数组工作正常,即如果$org除了'ACME'以外的任何东西,我得到的值(狗猫),但是如果$org等于'ACME'`我得到的值是2?

Any ideas?? 有任何想法吗??

Derefencing arrays is of course not forcing scalar context. 取消引用数组当然不会强制执行标量上下文。 But using || 但是使用|| is. 是。 Therefore things like $val = $special_val || "the default"; 因此,像$val = $special_val || "the default"; $val = $special_val || "the default"; work just fine while your example doesn't. 工作正常,而您的示例却没有。

Therefore @array will contain either a single number (the number of elements in the first array) or, if that is 0, the elements of the second array. 因此, @array array将包含一个数字(第一个数组中元素的数量),或者如果为0,则包含第二个数组中的元素。

The perlop perldoc page even lists this example speficially: perlop perldoc页面甚至perlop列出了此示例:

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

Depending on what you want, the solution could be: 根据您的需求,解决方案可能是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM