if I have a hash
my %foo = ( foo => 1, bar => 1 );
I want to check if any key of %foo is in a comparison array (and obviously keys %foo is just an array ). I keep thinking some weird syntax that does’t exist like.
my @cmp0 = qw( foo baz );
my @cmp1 = qw( baz blargh );
if keys %foo in @cmp0 # returns true because key foo is in the array
if keys %foo in @cmp1 # returns false because no key in foo is an element of cmp1
What is the simplest way to do this?
List::MoreUtils has a function called
anythat uses a syntax similar togrep, but stops its internal loop the first time the criteria are met. The advantage to this behavior is that far fewer iterations will be required (assuming random distribution of intersections).An additional advantage of
anyis code clarity: It is named for what it does. Perl Best Practices discourages usinggrepin Boolean context because the assumed use forgrepis to return a list of elements that match. It works in Boolean context, but the intent of the code is less clear to a reader thanany, which is designed specifically for Boolean usage.It is true that
anyadds a dependency on List::MoreUtils. However, List::MoreUtils is one of those modules that is so ubiquitous, it is highly likely to already be installed.Here’s an example:
Another option is the
~~Smart Match Operator, which became available in Perl 5.10.0 and newer. It could be used like this:With smartmatch, you eliminate the List::MoreUtils dependency in favor of a minimum Perl version dependency. It’s up to you to decide whether the code is as clear as
any.