Question

my %PlannedPerWeek = (
                    September => {
                            Week1 => [80, 23, 199, 45, 19, 36],
                            Week2 => [78, 21, 195, 43, 18, 36],
                            Week3 => [76, 19, 191, 41, 17, 36],
                            Week4 => [74, 17, 187, 39, 16, 36],
                    }
    );

I have the above hash of hash of arrays in a perl prog. How do I access element say '199' from the above data structure.

Was it helpful?

Solution

It's rather straightforward. The first one is a hash, so you don't need to dereference it. Every following 'container' inside your data structure is a reference, so you can use the -> operator to dereference that structure. Stuff that is inside curly brackets {} is a hash (key/value-pairs) reference and needs curlies to deref, while the stuff inside square brackets [] is an array reference and again needs square brackets do deref.

Now it's really just lining up the things and counting to 3:

print $PlannedPerWeek{'September'}->{'Week1'}->[2];
                                               ^---- 3rd array ref element
                                    ^--------------- hashref key 'Week1'
                      ^----------------------------- hash key 'September'

You can also leave out the arrows and just go:

print $PlannedPerWeek{'September'}{'Week3'}[2];

You should read perlreftut, which says:

In between two subscripts, the arrow is optional.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top