perl静态常量hashrefs

时间:2014-02-22 18:52:50

标签: perl static constants hashref

是否可以在perl中声明静态常量hashrefs? 我用以下方式尝试使用Readonly和Const :: Fast模块,但是当我多次调用sub时,会收到错误消息“尝试重新分配readonly变量”。

use Const::Fast;
use feature 'state';

sub test {
  const state $h => {1 => 1};
  #...
}

1 个答案:

答案 0 :(得分:2)

const是一个函数,每次调用test时都会调用它。这应该可以解决问题。

sub test {
   state $h;
   state $initialized;
   const $h => ... if !$initialized++;
   # ...
}

由于$h始终具有真值,我们可以使用以下内容:

sub test {
   state $h;
   const $h => ... if !$h;
   # ...
}

当然,您仍然可以使用旧的方法来执行持久的词法范围变量。

{
   const my $h => ...;

   sub test {
      # ...
   }
}
相关问题