perl - 可能对未定义的取消引用数组进行迭代是错误还是功能?

以下代码按预期崩溃,因为 $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/

相关文章:

python - 基于列内部索引对 Pandas 数据框进行分组

c# - 是否可以在不复制的情况下为多个组件创建一个 Blazor 范围的 CSS 文件?

java - 同时迭代三个列表

php - 元素临 : Change or remove category/tag/author p

python - 有没有办法在 python 列表中切换元素?

c# - 这个 C# 字符串格式的本质是什么?

c# - if else 语句简化以提高可读性

c# - EF Core EnsureDeleted 抛出 "failed to login wit

html - React Material UI-制作一个按钮打开文件选择器窗口

c++ - 如何在 C 中循环 if 语句