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

Hi Brethren,
How can I alter this code so that it prints out both the key and the value from the hash for each item in the array
foreach (@array){ print( $hash{$_}, "\n"); }

Thanks Gavin

Replies are listed 'Best First'.
Re: Printing items from an Hash using an Array
by ikegami (Patriarch) on Apr 11, 2006 at 21:47 UTC
    foreach (@array){ print( $_, ': ', $hash{$_}, "\n"); }
Re: Printing items from an Hash using an Array
by Zaxo (Archbishop) on Apr 12, 2006 at 01:46 UTC

    A refinement of ikegami's for when you want to skip items in @array which are not keys of %hash,

    for (grep {exists $hash{$_}} @array) { print $_, " :\t", $hash{$_}, "\n"; }

    After Compline,
    Zaxo

Re: Printing items from an Hash using an Array
by izut (Chaplain) on Apr 12, 2006 at 01:32 UTC
    You can do something like this:
    while (my ($k, $v) = each %hash) { print "$k: $v\n" }
    Where $k is the key and $v is the value.

    Igor 'izut' Sutton
    your code, your rules.