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


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?




How do I do a simple Perl hash equivalence comparison?

1:



How do you compare the content of two archive files programmatically?
You can use the Hash::Util module to lock and unlock a hash (keys, values, or both)..
How can I install a CPAN module into a local directory?
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:.
How can I tell if I'm running in a VMWARE virtual machine (from linux)?
use Foo; my $b = $Foo::MY_CONST{baz}{innerbar}; 


How do I include all/some of the “sub modules” in a Perl script?


How can I handle proxy servers with LWP::Simple?

2:



How can I use a code ref as a callback in Perl?
You can also do this entirely with builtins:.
Why can't I say print $somehash{$var}{fh} “foo”?
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};


3:


See Readonly:.
#!/usr/bin/perl  package Foo;  use strict; use warnings;  use Readonly;  Readonly::Hash our %h => (     a => { b => 1 } );  package main;  use strict; use warnings;  print $Foo::h{a}->{b}, "\n";  $h{a}->{b} = 2; 
Output:.
 C:\Temp> t 1 Modification of a read-only value attempted at C:\Temp\t.pl line 21 


4:


Here is a guide to hashes in perl.

Hash of Hashes.



85 out of 100 based on 45 user ratings 595 reviews