在 Perl 5.26 中,基于常量的哈希查找似乎是在编译时而不是运行时解析的。如何强制在运行时解析它?
考虑以下简化的测试用例,它是从我试图编写的基于哈希的状态机中总结出来的,其中键是状态标识符,值是状态函数。
use constant {
STATE_1 => 1,
STATE_2 => 2,
};
my %fsm;
%fsm = (
STATE_1, sub {
$fsm{STATE_2}->(@_);
return STATE_2;
},
STATE_2, sub {
return STATE_1;
}
);
my $state = STATE_1;
$state = $fsm{$state}->();
请注意,在 STATE_1
中,我尝试调用 STATE_2
函数。
但是,在运行时我得到了这个:
Can't use an undefined value as a subroutine reference at ./self-reference-hash.pl line 15.
这表明 STATE_1
中的 $fsm{STATE_2}->(@_);
行未定义。事实上,在该行首次出现时,STATE_2
函数尚未定义,但我指望在运行时解析哈希查找。
如果我将 $fsm{STATE_2}->(@_);
替换为 my $tmp = STATE_2; $fsm{$tmp}->(@_);
然后它按预期工作,这看起来很hacky。
有没有更干净的方法来做到这一点?
最佳答案
这个问题的根源实际上在Perl's doc about constant
中有解释。 ,这不是关于运行时与编译时的问题,而是关于 Perl 在某些上下文中神奇地引用裸字:
You can get into trouble if you use constants in a context which automatically quotes barewords (as is true for any subroutine call). For example, you can't say
$hash{CONSTANT}
becauseCONSTANT
will be interpreted as a string. Use$hash{CONSTANT()}
or$hash{+CONSTANT}
to prevent the bareword quoting mechanism from kicking in. Similarly, since the => operator quotes a bareword immediately to its left, you have to sayCONSTANT() => 'value'
(or simply use a comma in place of the big arrow) instead ofCONSTANT => 'value'
.
列出的解决方法可以解决该问题。
关于Perl:常量和编译时与运行时哈希查找?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51547738/