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

Hello wise ones I have two hashes, hashA and hashB. The values in hashA are the keys in hashB. I want to loop through hashA and print all of the values in hashB. The following code is what I expected to work, but it doesn't. Could anyone smarter than me tell me why? Thanks in advance.
while (($key, $value) = each(%hashA)){ print "$key = ".$hashB{$hashA{"${value}"}}."\n"; }
  • Comment on How can I print hash values when the keys are the values from another hash.
  • Download Code

Replies are listed 'Best First'.
Re: How can I print hash values when the keys are the values from another hash.
by ikegami (Patriarch) on Apr 06, 2006 at 17:31 UTC

    First, let's get rid of an abomination. Change
    "${value}"
    to
    $value

    The values in hashA are the keys in hashB.

    $value contains a value from hashA. Just use $value as the key to hashB. Change
    $hashB{$hashA{$value}}
    to
    $hashB{$value}

    Maybe you were thinking of
    $hashB{$hashA{$key}}
    which also works.

Re: How can I print hash values when the keys are the values from another hash.
by ptum (Priest) on Apr 06, 2006 at 17:31 UTC

    How about something like this (untested):

    foreach (keys %hashA) { print "$_ = $hashB{$hashA{$_}} \n"; }

    No good deed goes unpunished. -- (attributed to) Oscar Wilde
Re: How can I print hash values when the keys are the values from another hash.
by davido (Cardinal) on Apr 06, 2006 at 19:10 UTC

    How about this?:

    my %hashA = ( this => 'A', that => 'B', other => 'C' ); my %hashB = ( A => 'aye', B => 'bee', C => 'see' ); { local $" = "\n"; print "@hashB{ values( %hashA ) }\n"; }

    Dave

Re: How can I print hash values when the keys are the values from another hash.
by TedPride (Priest) on Apr 06, 2006 at 19:51 UTC
    print "$_ = $hashB{$_}\n" for sort keys %hashA;