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

Monks,
First I want to apologize for bringing this subject again. Last night I asked for advice in How to compare inner keys from two Hashes, and I kindly received a reply but I don't quite understand it.
Can somebody explain it to me?

Thank you very much!

Replies are listed 'Best First'.
Re: Some Explanation about inner hashes
by Limbic~Region (Chancellor) on Mar 30, 2004 at 18:45 UTC
    Anonymous Monk,
    If I understand your requirements:
    • Take action if a inner key exists as an inner key in another hash.
    • Know which value came from which hash/key
    • Take default action if no match
    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

      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