Search code examples
perlstaticconstantshashref

perl static constant hashrefs


Is it possible to declare static constant hashrefs in perl? I tried it with Readonly and Const::Fast module in the following way, but get the error message "Attempt to reassign a readonly variable" when I call the sub multiple times.

use Const::Fast;
use feature 'state';

sub test {
  const state $h => {1 => 1};
  #...
}

Solution

  • const is a function, and you're calling it every time test is called. This should do the trick.

    sub test {
       state $h;
       state $initialized;
       const $h => ... if !$initialized++;
       # ...
    }
    

    Since $h always has a true value, we can use the following:

    sub test {
       state $h;
       const $h => ... if !$h;
       # ...
    }
    

    Of course, you can still use the old way of doing persistent lexically-scoped variables.

    {
       const my $h => ...;
    
       sub test {
          # ...
       }
    }