Jordan
Jordan

Reputation: 311

How to find if values of an array are the keys of hash in Perl?

I have an array say @array. I would like to know which values of the array form the keys of a hash, say %hash. Is there is a simple way to do it other than using a for loop?

e.g.,

 @array = qw (a b c);   
 %hash = ( a => 1, b=> 2 );    

In this case it should just output 'a' and 'b'.

Upvotes: 7

Views: 186

Answers (1)

dgw
dgw

Reputation: 13646

This should do it:

my @array = qw(a b c) ;
my %hash = ( a => 1 , b => 2 ) ;

my @result = grep { exists $hash{$_} } @array ;

Upvotes: 17

Related Questions