masterial
masterial

Reputation: 2216

Conditional statement- compare to values store in array

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!";}

Upvotes: 0

Views: 422

Answers (4)

DVK
DVK

Reputation: 129559

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.

Upvotes: 5

Hugmeir
Hugmeir

Reputation: 1259

A 5.10+ solution: Use a smart-match!

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

Upvotes: 4

Jeff Hutton
Jeff Hutton

Reputation: 166

You could also use a hash:

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

Upvotes: 1

martin clayton
martin clayton

Reputation: 78225

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.

Upvotes: 1

Related Questions