为什么 map() 掩盖了“未定义值"错误? [英] Why does map() mask the 'undefined value' error?
问题描述
我想知道为什么在第二个代码段中调用 map
会导致未定义值"错误消失?
I'm wondering why a call to map
in the second snippet makes the 'undefined value' error gone?
use strict;
use warnings;
my $x;
my @a = @{ $x }; # error: Can't use an undefined value as an ARRAY reference
比较:
use strict;
use warnings;
my $x;
my @a = map $_, @{ $x }; # no error, @a is empty
推荐答案
这是由于 map() 做别名(它本质上是使用 for()
循环).正在发生的事情是 aref 正在左值上下文中使用,因此正在 auto-vivified 存在.
This is due to the way that map() does aliasing (it's essentially using a for()
loop). What's happening is that the aref is being used in l-value context, and therefore is being auto-vivified into existence.
在您之前的示例中,您试图直接在 r 值上下文中使用 aref,这就是它生成错误的原因(因为没有发生自动激活).
In your former example, you're attempting to use the aref directly in r-value context, which is why it generates the error (because no auto-vivification happens).
您可以简化您的测试以使用 for()
,并且您将获得与 map()
相同的结果:
You can simplify your test to use for()
, and you'll get the same result as with map()
:
use warnings;
use strict;
my $x;
for (@{ $x }){
print "$_\n";
}
...没有输出.
要直观地看到 $x
被自动激活为数组引用,您可以使用 ref() 函数:
To visually see that $x
was auto-vivified as an array reference, you can use the ref() function:
my $x;
my @a = map $_, @{ $x };
print ref $x;
输出:
ARRAY
这篇关于为什么 map() 掩盖了“未定义值"错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!