Search code examples
perlhashconstantsperl-data-structures

How can I create a nested hash as a constant in Perl?


I want to do, in Perl, the equivalent of the following Ruby code:

class Foo
  MY_CONST = {
    'foo' => 'bar',
    'baz' => {
      'innerbar' => 'bleh'
    },
  }

  def some_method
    a = MY_CONST[ 'foo' ]
  end

end

# In some other file which uses Foo...

b = Foo::MY_CONST[ 'baz' ][ 'innerbar' ]

That is, I just want to declare a constant, nested hash structure for use both in the class and outside. How to?


Solution

  • You can use the Hash::Util module to lock and unlock a hash (keys, values, or both).

    package Foo;
    use Hash::Util;
    
    our %MY_CONST = (
        foo => 'bar',
        baz => {
            innerbar => 'bleh',
        }
    );
    
    Hash::Util::lock_hash_recurse(%MY_CONST);
    

    Then in some other file:

    use Foo;
    my $b = $Foo::MY_CONST{baz}{innerbar};