【问题标题】:perl static constant hashrefsperl 静态常量 hashrefs
【发布时间】:2014-02-22 18:52:49
【问题描述】:

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

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

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

【问题讨论】:

    标签: perl static constants hashref


    【解决方案1】:

    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 {
          # ...
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-02
      • 2013-06-13
      • 2012-01-25
      • 1970-01-01
      • 1970-01-01
      • 2012-06-06
      • 1970-01-01
      相关资源
      最近更新 更多