7

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

3
  • 3
    You've got some bareword problems if you're using use strict; (and you should be). Commented Jun 8, 2012 at 18:53
  • Right. If that array is supposed to contain the literal letters 'a', 'b', and 'c', it should be either @array = ('a','b','c'); or @array = qw(a b c); Commented Jun 8, 2012 at 19:00
  • @JonathanLeffler: I use strict, I just didn't include it in the example. Commented Jun 8, 2012 at 19:39

1 Answer 1

17

This should do it:

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

my @result = grep { exists $hash{$_} } @array ;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.