perl - 为什么我们不能在列表上下文中初始化状态数组/哈希?

标签 perl initialization

数组和散列作为状态变量存在限制。从 Perl 5.10 开始,我们无法在列表上下文中初始化它们:

所以

state @array = qw(a b c); #Error!

为什么会这样?为什么这是不允许的?

我们可以使用状态数组并通过这种方式初始化它们
state @numbers;
push @numbers, 5;
push @numbers, 6;

但为什么不直接通过 state @numbers = qw(5 6); 来做?

为什么 Perl 不允许?

最佳答案

根据 perldiag ,计划在 future 版本中支持列表上下文初始化:

  • Initialization of state variables in list context currently forbidden
    (F) Currently the implementation of "state" only permits the initialization of scalar variables in scalar context. Re-write state ($a) = 42 as state $a = 42 to change from list to scalar context. Constructions such as state (@a) = foo() will be supported in a future perl release.


根据 this message about the change that made this an error :

For now, forbid all list assignment initialisation of state variables, as the precise semantics in Perl 6 are not clear. Better to make it a syntax error, than to have one behaviour now, but change it later. [I believe that this is the consensus. If not, it will be backed out]



您始终可以使用 arrayref 代替:
state $arrayRef = [qw(a b c)];

请注意,您的示例
state @numbers;
push @numbers, 5;
push @numbers, 6;

不是 state @numbers = qw(5 6) 的意思相同会(如果它有效)。 A state变量仅初始化一次,但每次执行该代码时,您的代码都会将 5 和 6 插入数组。

关于perl - 为什么我们不能在列表上下文中初始化状态数组/哈希?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6702666/

相关文章:

c++ - 按范围初始化数组

c++ - 我必须使用 0.f 初始化 float 吗?

ios - 使用 map() 从字典数组(即 JSON 数组)初始化数组内联

c - 将整数数组初始化为成员

java - 如何检测一个 Java 类是被它自己的 main() 调用还是被另一个类调用?

perl - perl 中未提供文件名时如何使用 __DATA__ 句柄

php - 比较两个具有相同结构的 XML 文件并找出差异

非贪婪匹配不同行为的正则表达式

perl - 为什么这个 Mojolicious websockets 示例不起作用?

linux - 无法在 @INC 中找到 Core/Utility.pm