Perl: constants and compile-time vs runtime hash lookups?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Perl: constants and compile-time vs runtime hash lookups?



In Perl 5.26, constant-based hash lookups appear to be resolved at compile-time, not runtime. How can I enforce it to be resolved at runtime?



Consider the following reduced testcase, boiled down from a hash-based state-machine I was trying to write, where the key is the state identifier and the value is the state function.


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}->();



Note that in STATE_1, I'm trying to call the STATE_2 function.


STATE_1


STATE_2



However, at runtime I get this:


Can't use an undefined value as a subroutine reference at ./self-reference-hash.pl line 15.



Which indicates that the $fsm{STATE_2}->(@_); line in STATE_1 is undefined. And indeed, at the time where this line first appears, the STATE_2 function isn't defined yet, but I was counting on hash lookups being resolved at runtime.


$fsm{STATE_2}->(@_);


STATE_1


STATE_2



If I instead replace $fsm{STATE_2}->(@_); with my $tmp = STATE_2; $fsm{$tmp}->(@_); then it works as expected, which seems hacky.


$fsm{STATE_2}->(@_);


my $tmp = STATE_2; $fsm{$tmp}->(@_);



Is there a cleaner way to do this?





Wouldn't use Const::Fast; const my $STATE_1 => 1; work?
– zdim
31 secs ago


use Const::Fast; const my $STATE_1 => 1;









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Visual Studio Code: How to configure includePath for better IntelliSense results

Spring cloud config client Could not locate PropertySource

Makefile test if variable is not empty