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

Hi. How do I traverse a double hash? Namely, I put into a hash by
myHash{Value1}{Value2} = foobar;
I first traverse myHash on value1 by
foreach my $key1 (sort keys %myhash) { ## But now how do I traverse on key 2 based on key 1?? }
Any help would be appreciated.

Replies are listed 'Best First'.
Re: Traversing a double hash
by btrott (Parson) on Apr 16, 2000 at 04:26 UTC
    Each value in the hash is a hash reference, so you need to dereference the hash reference, then just treat it like a regular hash. Take a look at perlref. Here's some code:
    for my $key1 (sort keys %myhash) { print $key1, "\n"; for my $key2 (sort keys %{$myhash{$key1}}) { print "\t", $key2, " => ", $myhash{$key1}{$key2}, "\n"; } }
    If you just want to see what a data structure contains, use Data::Dumper:
    use Data::Dumper; print Dumper \%myhash;
      Just used this logic on a triple hash! Works beautifully!
      for my $key1 (sort keys %linehash) { $outSect1 = $key1; for my $key2 (sort keys %{$linehash{$key1}}) { $outSect2 = "$outSect1.$key2"; print "$outSect2\n"; for my $key3 (sort keys %{$linehash{$key1}{$key2}}) { if ($key3 ne ""){ print "\t", $key3, " = ", $linehash{$key1}{$key2}{$key3} +, "\n"; } } } }
      Your humble servant,
      -Chuck
      Thank you!
Re: Traversing a double hash (kudra: some code)
by kudra (Vicar) on Apr 17, 2000 at 12:21 UTC
    I think you might be able to do this, if I correctly understood what you want to do:
    # Assume you already have $key1 foreach $key2 (keys %{$myhash{$key1}}) { print "Key: $key2\nValue: "; print $myhash{$key1}{$key2}."\n\n"; }
Re: Traversing a double hash
by zebroz (Initiate) on Apr 18, 2000 at 08:32 UTC
    Sweet thanks. :)
A reply falls below the community's threshold of quality. You may see it by logging in.