加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 22:03:58 所属栏目:大数据 来源:网络整理
导读:数组和哈希作为状态变量有限制.在Perl 5.10中,我们无法在列表上下文中初始化它们: 所以 state @array = qw(a b c); #Error! 为什么会这样?为什么不允许? 我们可以使用状态数组,并通过这种方式初始化它们 state @numbers;push @numbers,5;push @numbers,6;
数组和哈希作为状态变量有限制.在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&每次执行该代码时,都会将该数组写入数组.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读