是否可以在 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 {
# ...
}
}