How to declare AoHoAoH?

156 Views Asked by At

I have this output from Dumper

'group' => {
             '1104' => {
                         'a' => 1
                       },
             '52202' => {
                          'b' => 1,
                          'c' => 1
                        },
             '52201' => {
                          'c' => 1
                        },
             '52200' => {
                          'c' => 1
                        }
           },

which I assume is an Array of Hashes of Arrays of Hashes?

I would like to declare this structure my self.

Is there a way to do this, so next time I see such a complex structure, I can do that in no time? =)

2

There are 2 best solutions below

0
On BEST ANSWER

Since the types of variables, and of hash values, can change in Perl, there isn't any way to "declare" a three-level hash the way you're probably thinking. You can instantiate an empty hashref into each key as it's created, which is a similar idea:

# First pass
my $data = {};

# Later...
$data->{group} = {};

# Still later...
$data->{group}->{1104} = {};

# Finally... 
$data->{group}->{1104}->{a} = 1;

But you could just as easily simply fill in the data as you obtain it, allowing autovivification to do its thing:

my $data;

# Fill one piece of data... Perl creates all three hash levels now.
$data->{group}->{1104}->{a} = 1; 

# Fill another piece of data, this one has two values in the "bottom" hash.
$data->{group}->{52202} = { b => 1, c => 2};

But there is no way (in plain Perl) to "enforce" that the values for any particular key contain hashes rather than strings or subroutine references, which is usually what is intended by declaration in languages with C-like type systems.

3
On

Your output is a hash of hashes of hashes, with the first hash only containing a single element. The {} mark a hash reference, so you'd repeat your data structure thus, where the resulting $hohoh is a refrence to a HoHoH.

my $hohoh = {
    'group' => {
         '1104' => {
                     'a' => 1
                   },
         '52202' => {
                      'b' => 1,
                      'c' => 1
                    },
         '52201' => {
                      'c' => 1
                    },
         '52200' => {
                      'c' => 1
                    }
       },
};
print $hohoh->{group}{1104}{a}; # -> 1

I recommend reading the Perl Datastructures Cookbook.