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

Hi Monks, Can someone tell me what is Hash of Hash table? Can someone give me an example of that? I am trying to see if I can applay that when I try to have tow values as one key . I mean if I have a line in my file that look like this  one tow three four five six and I want to have one and tow as key for the rest of the line. right now I will have to have tow hashes as follow:
%one; %tow; while (<INPUT>) { chomp(my @line = split/\s+/); push @{$one{$r[0]}}, [ @line[1..$#r] ]; push @{$tow{$r[1]}}, [ @line[2..$#r] ]; }
I need to some how merge it into one hash . Maybe if I understand Hash of Hash , I will be able to see if my approach is possible. Thanks all

Replies are listed 'Best First'.
Re: Hash of Hash
by jeffa (Bishop) on Feb 28, 2004 at 23:20 UTC
    A Hash of Hashes simply looks something like:
    $ perl -MData::Dumper -e"%h=(a=>{1..4},b=>{5..8});print Dumper\%h" $VAR1 = { 'a' => { '1' => 2, '3' => 4 }, 'b' => { '7' => 8, '5' => 6 } };
    What you probably want instead is a Hash of Lists. Try this:
    use strict; use warnings; use Data::Dumper; ... my %hash; while (<INPUT>) { chomp; my @line = split /\s+/, $_; my ($key1,$key2) = (shift @line, shift @line); $hash{$key1} = $hash{$key2} = [@line]; } print Dumper \%hash;

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: Hash of Hash
by neniro (Priest) on Feb 28, 2004 at 23:17 UTC
    I'm not sure, but you can use a reference for this purpose:
    #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $string = q(one tow three four five six); my @words = split(/ /, $string); my %hash1; my %hash2; $hash2{$words[1]} = join(" ", @words[2..5]); $hash1{$words[0]} = \%hash2; print Dumper(%hash1);
    best regards neniro
      Just a hint. Instead of
      my $string = q(one tow three four five six); my @words = split(/ /, $string);
      You might want to use
      my @words= qw(one tow three four five six);
      As you no longer use $strings, there is no need for you to split on that.

      And as you don't really have a need for $hash2, this might help by using an anonymous hash:
      $hash1{$words[0]}= { $words[1] => join(' ', @word[2..$#words]) };
Re: Hash of Hash
by Skeeve (Parson) on Feb 29, 2004 at 00:12 UTC
    To create a hash of hashes for that line, you can do this:
    my %hash_of_hashes= ( one => { two => 'three four five' } );
    A hash of hashes is a simple hash, where each value is a pointer to another hash.
    To see how this looks like try this:
    use strict; use warnings; use Data::Dumper; my %hash_of_hashes= ( one => { two => 'three four five' } ); print Dumper \%hash_of_hashes;