Withnail has asked for the wisdom of the Perl Monks concerning the following question:

I have a problem with accessing data from a 3D hash. I've tried scaling the hash structure from a 2D hash, whcuh I can access fine via nested for loops. However, I can't get access a 3D hash. I'd like some help, please. Here's my code, (also posted on my scratchpad):
%ThreeD = ( TV => { version3 => { lead => "fred", pal => "barney", }, }, ); # print the whole thing foreach $media ( keys %ThreeD) { print "$media @ {"; for $media_ver ( keys %{ $ThreeD{$media_ver} } ) { print "$media_ver { "; for $leaf_obj ( keys %{ $ThreeD{$media{$media_ver}} } ) { print "$leaf_obj=$ThreeD{$media}{$media_ver}{$leaf_obj} "; } } print "}\n"; }
Perhaps I have constructed the hash incorrectly? I feel the answer is more likely that my inner loop 'for' is set up incorrectly or that its inner-most print statement is incorrect. I searched all over for an example of a 3D hash, but have found nothing. Is this possible in Perl!!?!?

Replies are listed 'Best First'.
Re: 3D Hash
by kyle (Abbot) on Jul 14, 2007 at 05:38 UTC

    If you're just trying to visualize your data, have a look at Data::Dumper.

    Otherwise, with a few modifications, your code works.

    use strict; use warnings; use Data::Dumper; my %ThreeD = ( TV => { version3 => { lead => "fred", pal => "barney", }, }, ); print Dumper( \%ThreeD ); # print the whole thing foreach my $media ( keys %ThreeD) { print "$media @ {"; for my $media_ver ( keys %{ $ThreeD{$media} } ) { print "$media_ver { "; for my $leaf_obj ( keys %{ $ThreeD{$media}{$media_ver} } ) { print "$leaf_obj=$ThreeD{$media}{$media_ver}{$leaf_obj} "; } } print "}\n"; } __END__ $VAR1 = { 'TV' => { 'version3' => { 'lead' => 'fred', 'pal' => 'barney' } } }; TV @ {version3 { lead=fred pal=barney }

    Always use strict. It highlighted one of your errors for me. Specifically, you used $media_ver before it was defined. The other problem I found was just that your syntax for accessing the second level down was wrong (it's $ThreeD{$media}{$media_ver}).

Re: 3D Hash
by BrowserUk (Patriarch) on Jul 14, 2007 at 05:44 UTC