I\'m looking for presence of an element in a list.
In Python there is an in
keyword and I would do something like:
if element in list:
On perl >= 5.10 the smart match operator is surely the easiest way, as many others have already said.
On older versions of perl, I would instead suggest List::MoreUtils::any.
List::MoreUtils
is not a core module (some say it should be) but it's very popular and it's included in major perl distributions.
It has the following advantages:
in
does) and not the value of the element, as List::Util::first
does (which makes it hard to test, as noted above);grep
, it stops at the first element which passes the test (perl's smart match operator short circuits as well);Here is an example which works with any searched (scalar) value, including undef
:
use List::MoreUtils qw(any);
my $value = 'test'; # or any other scalar
my @array = (1, 2, undef, 'test', 5, 6);
no warnings 'uninitialized';
if ( any { $_ eq $value } @array ) {
print "$value present\n"
}
(In production code it's better to narrow the scope of no warnings 'uninitialized'
).