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

前端之家收集整理的这篇文章主要介绍了perl – 为什么我们不能在列表上下文中初始化状态数组/哈希?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
数组和哈希作为状态变量有限制.在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,计划在未来版本中支持列表上下文初始化:
  • 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,6;

并不意味着状态@numbers = qw(5 6)将(如果它工作)相同的事情.状态变量只能初始化一次,但是你的代码会推送5&每次执行该代码时,都会将该数组写入数组.

猜你在找的Perl相关文章