是否可以在 Perl 中声明静态常量 hashrefs? 我按照以下方式尝试使用 Readonly 和 Const::Fast 模块,但是当我多次调用 sub 时收到错误消息“尝试重新分配只读变量”。
use Const::Fast;
use feature 'state';
sub test {
const state $h => {1 => 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 {
# ...
}
}
关于Perl 静态常量 hashrefs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21958868/