gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:12:50 27 4
gpt4 key购买 nike

数组和散列作为状态变量存在限制。从 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com