以下代码按预期崩溃,因为 $x
不包含数组引用:
$ perl -E 'use strict; use warnings; my $x; say @{$x}; say "OK";'
Can't use an undefined value as an ARRAY reference at -e line 1.
然而这段代码在没有任何警告的情况下工作:
perl -E 'use strict; use warnings; my $x; say for @{$x}; say "OK";'
OK
为什么?我没有在 perldoc 中找到任何关于此行为的文档。
看起来 for
上下文在这里暗示了一些 DWIM-ness 逻辑(具有危险的后果)。
最佳答案
希望这有点启发:
$ perl -E 'use strict; use warnings; my $x; say for @{$x}; say $x;'
ARRAY(0x561b92479420)
$x
变量正在被 for
自动生成。
比较:
$ perl -E 'use strict; use warnings; my $x; $x->[0]; say $x;'
Useless use of array element in void context at -e line 1.
ARRAY(0x561b92479420)
对未定义标量的某些引用操作将导致自动生成发生。 for @{$var}
显然是其中之一。有一个autovivication CPAN 上的模块可让您更好地控制自动激活发生的时间。
https://stackoverflow.com/questions/64873766/