in reply to comparing array elements to hash keys

Much easier with grep.

@new_array = @hash{ grep { exists $hash{$_} } @array };
--
<http://www.dave.org.uk>

"The first rule of Perl club is you do not talk about Perl club."
-- Chip Salzenberg

Replies are listed 'Best First'.
Re: Re: comparing array elements to hash keys
by dvergin (Monsignor) on Jul 03, 2003 at 19:53 UTC
    I was going to suggest:
    my @ary2 = grep {defined} @hash{@ary};
    It's tempting to just say   my @ary2 = @hash{@ary}.   But the values in @ary that don't match keys in %hash produce undefined values that have to be weeded out.

    Here's a quick demo:

    #!/usr/bin/perl -w use strict; my @ary = ('a', 'c', 'g', 'l'); my %hash = (a => 1, b => 2, c => 3, d => 4); my @ary2 = grep {defined} @hash{@ary}; print "[$_]\n" for @ary2;