取消引用未定义的数组引用时的Perl vivification问题 [英] Perl vivification question while dereferencing undefined array reference
本文介绍了取消引用未定义的数组引用时的Perl vivification问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很难理解以下原因:
my $array_reference;
foreach $element (@{$array_reference}) {
# some code
}
以下内容不起作用
my $array_reference;
if (scalar (@{$array_reference}) {
# some code here
}
我知道perl使未定义的引用栩栩如生(自动更新).但是我仍然很困惑,为什么后面的代码段会抛出致命错误.
I understand that perl brings to life (auto-vivifies) undefined reference. But I am still confused as in why the latter code segment throws FATAL.
推荐答案
在lvalue上下文中(即当期望可修改的值时)自动取消引用,并foreach创建一个lvalue上下文.
Dereferences autovivify in lvalue context (meaning when a modifiable value is expected), and foreach create an lvalue context.
>perl -E"$$x = 1; say $x;"
SCALAR(0x74b024)
>perl -E"++$$x; say $x;"
SCALAR(0x2eb024)
>perl -E"\$$x; say $x;"
SCALAR(0x30b024)
>perl -E"sub {}->($$x); say $x;"
SCALAR(0x27b03c)
>perl -E"for ($$x) {} say $x;"
SCALAR(0x25b03c)
最后两个创建左值上下文,因为它们需要一个分别为$_[0]
和$_
别名的值.
The last two create an lvalue context because they need a value to which to alias $_[0]
and $_
(respectively).
这篇关于取消引用未定义的数组引用时的Perl vivification问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文