0

Need help figuring out working perl code to put in place of "any of the elements in @array"

%hash = (key1 => 'value1',key2 => 'value2',key3 => 'value3',);

@array= ('value3','value4','value6'); 

if ($hash{ 'key1' } ne <<any of the elements in @array>>) {print "YAY!";}

4 Answers 4

5

CPAN solution: use List::MoreUtils

use List::MoreUtils qw{any}; 
print "YAY!" if any { $hash{'key1'} eq $_ } @array;

Why use this solution over the alternatives?

  • Can't use smart match in Perl before 5.10

  • grep solution loops through the entire list even if the first element of 1,000,000 long list matches. any will short-circuit and quit the moment the first match is found, thus it is more efficient.

Sign up to request clarification or add additional context in comments.

Comments

4

A 5.10+ solution: Use a smart-match!

say 'Modern Yay!' unless $hash{$key} ~~ @array;

Comments

1

You could use the grep function. Here's a basic example:

print "YAY!" if grep { $hash{'key1'} eq $_ } @array;

In a scalar context like this grep will give you the number of matching entries in @array. If that's non-zero, you have a match.

1 Comment

Caveat: grep solution loops through the entire list even if the first element of 1,000,000 long list matches.
1

You could also use a hash:

@hash{"value3","value4","value6"}=undef;
print "YAY" if exists $hash{key1};

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.