Flickr

Social Stuff
Site Info

Sponsored Links

Laurie's Entries

« MatrixStream and Movie99 | Main | Installing Perforce on Linux »

Perl: Iterating and Assigning Hash of Hashes and the Enigmatic Search

So, I was trying to do something simple.  I had a normal, everyday hash of hashes in perl.  That is, something where you have the likes:

$var{$key1}{$subkey1} = $value1;
$var{$key1}{$subkey2} = $value2;
$var{$key2}{$subkey1} = $value3;
$var{$key2}{$subkey2} = $value4;


Now, anyone can iterate over a normal hash:

foreach $key (keys %var)
{
    print "$key = $var{$key}";
}
But if these are hashes, this won't work.  You might think you just iterate over the next level of hash:

foreach $key (keys %var)

{

    print "$key = $var{$key}";
    foreach $subkey (keys $var{$key})
    {
       print "$subkey = $var{$key}{$subkey};
    }

}
#or this
foreach $key (keys %var)

{
    %subhash = $var{$key};

    print "$key = $var{$key}";

    foreach $subkey (keys %subhash)

    {

       print "$subkey = $subhash{$subkey};

    }

}



This won't even compile -- "$var{$key}" isn't a hash! (It's actually the text "HASH xxx", I think.) The key to this is simple, but finding the solution wasn't because it's not a topic on it's own.  All of you have to do is basically cast it:

foreach $key (keys %var)

{

    print "$key = $var{$key}";

    foreach $subkey (keys %{$var{$key}})

    {

       print "$subkey = $var{$key}{$subkey};

    }

}
#or this

foreach $key (keys %var)


{

    %subhash = %{$var{$key}};


    print "$key = $var{$key}";

    foreach $subkey (keys %subhash)

    {

       print "$subkey = $subhash{$subkey};

    }


}




I never did find a description of this, but I first saw it when googling at the site listed below.  I wouldn't consider this advanced, or even intermediate, really.  It was just particularly difficult to find.  And the results -- or even compile errors -- listed didn't help find a solution any faster.  So how would you search to find the answer to this?

! Aware to Perl: Access and Printing of a HASH OF HASHES

Posted by Shane on March 21, 2006 10:49 AM |

TrackBacks

TrackBack URL for this entry:
http://www.kf6nvr.net/mt/kf6nvr-tb.cgi/706
1