Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 904
Pistos Avatar asked Jul 31 '09 19:07

Pistos


People also ask

How do I access nested hash in Perl?

Nested hashes are addressed by chaining the keys like so: $hash{top_key}{next_key}{another_key}; # for %hash # OR $hash_ref->{top_key}{next_key}{another_key}; # for refs. However since both of these "hashes" are blessed objects.

How to dereference a hash reference in Perl?

Dereferencing is the way of accessing the value in the memory pointed by the reference. In order to dereference, we use the prefix $, @, % or & depending on the type of the variable(a reference can point to a array, scalar, or hash etc).

How will you get all keys from hashes in Perl and all values from hashes in Perl?

In Perl, hash data structure is provided by the keys() function similar to the one present in Python programming language. This keys() function allows you to get a list of keys of the hash in scalars which can be further used to iterate over the values of respective keys of the hash.


1 Answers

You can also do this entirely with builtins:

package Foo;
use constant MY_CONST =>
{
    'foo' => 'bar',
    'baz' => {
        'innerbar' => 'bleh',
    },
};

sub some_method
{
    # presumably $a is defined somewhere else...
    # or perhaps you mean to dereference a parameter passed in?
    # in that case, use ${$_[0]} = MY_CONST->{foo} and call some_method(\$var);
    $a = MY_CONST->{foo};
}

package Main;  # or any other namespace that isn't Foo...
# ...
my $b = Foo->MY_CONST->{baz}{innerbar};
like image 106
Ether Avatar answered Nov 09 '22 00:11

Ether