in reply to hashes: testing for the presence of a key

The essence of the answer is to iterate over the array of various numbers (@array) and test for each in the hash, rather than vice versa, which is what you attempted to do. It is easier both to iterate over an array, and to test for existence in a hash.
for ( @array ) { if ( exists $hash{$_} ) { push @found, $_ . $hash{$_}; } }
You could reduce the above to this:
push @found, map { $_ . $hash{$_} } grep { exists $hash{$_} } @array;
Or even
push @found, map { exists $hash{$_} ? $_ . $hash{$_} : () } @array;

jdporter
The 6th Rule of Perl Club is -- There is no Rule #6.

Replies are listed 'Best First'.
Re: Re: hashes: testing for the presence of a key
by BrowserUk (Patriarch) on May 15, 2003 at 14:20 UTC

    Unless @found has pre-existing contents, you can drop the push as well.

    my @a = ( 1, 3, 5, 7, 9, 11 ); my @hash{ 1 .. 10 } = 'a' .. 'j'; my @found = map{ exists $hash{$_} ? "$_$hash{$_}" : () } @a; print "@found"; 1a 3c 5e 7g 9i

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller