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?
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.
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).
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.
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};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With