Alex Rivera | Logout

Perl: if ( element in list )

Asked 2010-03-04T23:32:00.093
83

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:
    doTask

Is there something equivalent in Perl without having to manually iterate through the entire list?

Edit
Report

3 Answers

10

grep is helpful here

if (grep { $_ eq $element } @list) {
    ....
}
answered 2010-03-04T23:33:45.653
9

List::Util::first

$foo = first { ($_ && $_ eq "value" } @list;    # first defined value in @list

Or for hand-rolling types:

my $is_in_list = 0;
foreach my $elem (@list) {
    if ($elem && $elem eq $value_to_find) {
        $is_in_list = 1;
        last;
    }
}
if ($is_in_list) {
   ...

A slightly different version MIGHT be somewhat faster on very long lists:

my $is_in_list = 0;
for (my $i = 0; i < scalar(@list); ++$i) {
    if ($list[i] && $list[i] eq $value_to_find) {
        $is_in_list = 1;
        last;
    }
}
if ($is_in_list) {
   ...
answered 2010-03-04T23:55:01.980
2

This blog post discusses the best answers to this question.

As a short summary, if you can install CPAN modules then the best solutions are:

if any(@ingredients) eq 'flour';

or

if @ingredients->contains('flour');

However, a more usual idiom is:

if @any { $_ eq 'flour' } @ingredients

which i find less clear.

But please don't use the first() function! It doesn't express the intent of your code at all. Don't use the "Smart match" operator: it is broken. And don't use grep() nor the solution with a hash: they iterate through the whole list. While any() will stop as soon as it finds your value.

Check out the blog post for more details.

PS: i'm answering for people who will have the same question in the future.

answered 2013-05-22T12:02:32.227

Your Answer