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

Hi all ! First of all, thanks to everyone who replied on the previous multi-level question. I'm very well surprised by the level of the replies - I already have something working and got some mor einsight into Perl. Thanks ! Now, on the same subject, I have this multi-level hash and I'd like to loop on a hash that's declared inside another one. I can easily loop on the top declarations (Project1, Project2, Project3) like this:
while(($key, $value) = each(%projects)) { print "DEBUG $key = $value\n"; }
But how about looping on Porject1's components (Software, Firmware) or the Project1 Software's own sub components (Database, SerialComms) ? Here's the structure (please don't look at it for syntax - it's mostly a representation I've made) :
%projects = ( Projects => { "Project1" => { version => "3.41", status => "nul", components => { "Software" => { name => "controller", label => "RC_1.01", subComponents => { "Database" => { version = "1.01", } "SerialComms" => { version = "2.13", } } "Firmware" => { name => "I/O Interface", label => "RC_1.21", } } } "Project2" => { } "Project3" => { } )
Cheers.

Replies are listed 'Best First'.
Re: Accessing multi-level hashes
by pg (Canon) on Oct 29, 2005 at 17:01 UTC

    The definition of your hash has quite a few problems, such as missing comma, missing end }, misusing = where needs =>. Also top level "Projects" is useless, unless you have something else at the same level (which you didn't show)

    Here is an example as how you can go through subcomponents of softwares:

    use Data::Dumper; use strict; use warnings; my %projects = ( Projects => { "Project1" => { version => "3.41", status => "nul", components => { "Software" => { name => "controller", label => "RC_1.01", subComponents => { "Database" => { version => "1.01", }, "SerialComms" => { version => "2.13", } } }, "Firmware" => { name => "I/O Interface", label => "RC_1.21", } } }, "Project2" => { }, "Project3" => { } } ); for my $project_key (keys(%{$projects{"Projects"}})) { print "$project_key:\n"; my $project = $projects{"Projects"}->{$project_key};#this looks no +t necessary here, but in more complex code, it does help to simplify +things if (defined($project->{"components"}{"Software"})) { for my $subcomponents_key (keys(%{$project->{"components"}{"So +ftware"}{"subComponents"}})) { print $subcomponents_key, ":\n"; print Dumper($project->{"components"}{"Software"}{"subComp +onents"}{$subcomponents_key}); } } }

    this gives:

    Project3: Project1: Database: $VAR1 = { 'version' => '1.01' }; SerialComms: $VAR1 = { 'version' => '2.13' }; Project2:
Re: Accessing multi-level hashes
by planetscape (Chancellor) on Oct 30, 2005 at 12:07 UTC