[英]Perl: dereferencing an array is using scalar context?
我對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?
有任何想法嗎??
取消引用數組當然不會強制執行標量上下文。 但是使用||
是。 因此,像$val = $special_val || "the default";
$val = $special_val || "the default";
工作正常,而您的示例卻沒有。
因此, @array
array將包含一個數字(第一個數組中元素的數量),或者如果為0,則包含第二個數組中的元素。
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
根據您的需求,解決方案可能是:
my @array = @{$INI{$org}->{animals}}
? @{$INI{$org}->{animals}}
: @{$INI{Common}->{animals}};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.