in reply to Some Explanation about inner hashes

Anonymous Monk,
If I understand your requirements: The clearest way I can think to do this is to walk through the all the keys of the second hash for each inner key in the first hash. The only optimization I have done is return once a match is found.
#!/usr/bin/perl use strict; use warnings; my %hash1 = ( foo => { 'a' => 1, 'b' => 2, 'c' => 3 }, bar => { 'd' => 1, 'e' => 2, 'f' => 3 }, ); my %hash2 = ( blah => { 'm' => 1, 'd' => 2, 'a' => 3 }, asdf => { 'z' => 1, 'l' => 2, 'b' => 3 }, ); for my $outer_key ( keys %hash1 ) { for my $inner_key ( keys %{ $hash1{$outer_key} } ) { my ($h2_outer, $h2_inner) = Find_Key( $inner_key , \%hash2 ); if ( $h2_inner ) { # do something : $outer_key, $inner_key, $h2_outer, and $h +2_inner } else { # do your other thing } } } sub Find_Key { my ($match, $hash) = @_; for my $key ( keys %$hash ) { for ( keys %{ $hash->{$key} } ) { return ($key, $_) if $_ eq $match; } } return (undef, undef); }
If this code is not any clearer, please let me know and I will give a blow by blow explanation.

Cheers - L~R

Replies are listed 'Best First'.
Re: Re: Some Explanation about inner hashes
by Anonymous Monk on Mar 30, 2004 at 19:23 UTC
    Thank you L~R
    This code was much clear to me, only one question should I also return the value of the $h2_inner(key) in the sub?
      Anonymous Monk,
      That is a matter of personal choice.

      The values can be looked up once the keys are known regardless of where in the code you are.

      There are also ways to make optimizations to this code that might make it less clear what is going on. When trying to understand something that seems complex it is often beneficial to work with a foundation that you fully understand and then add the complexity piece by piece.

      Cheers - L~R

        Thanks L~R for your advice and answer