How to declare AoHoAoH?

Question!

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? =)



Answers

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.



This video can help you solving your question :)
By: admin