Perl:常量和编译时与运行时哈希查找?

标签 perl hash constants

在 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} because CONSTANT 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 say CONSTANT() => 'value' (or simply use a comma in place of the big arrow) instead of CONSTANT => 'value' .

列出的解决方法可以解决该问题。

关于Perl:常量和编译时与运行时哈希查找?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51547738/

相关文章:

perl - 如何在Perl中X个字符后添加换行符?

python - 拥有不可散列的类是不是 unpythonic?

c++ - const 到非常量 c++

perl - 如何使基于 Dist::Zilla 的 Perl 模块(或应用程序)安装文件到/etc/?

windows - #!/usr/bin/perl 不需要在 Windows 中运行 perl,但是

Perl 哈希对键和值进行排序

android - 为 Android 中的 Facebook 应用程序生成 key 哈希

c - 如何使用 Math.h 中的 M_LN2

c++ - 我不知道如何制作 "const unsigned float&"

performance - Perl Goatse 'Secret Operator' 有效吗?