Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

hash

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'.

like image 317
Jordan Avatar asked Jun 08 '12 18:06

Jordan


1 Answers

This should do it:

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

my @result = grep { exists $hash{$_} } @array ;
like image 191
dgw Avatar answered Sep 23 '22 05:09

dgw