in reply to Re: If any element-in-array comparision
in thread If any element-in-array comparision

I've seen List:Util::first mentioned a couple of times, and agree that will work fine. I recommend List::MoreUtils::any, however, as its meaning and intent is clearer since it has a name that matches the problem.

(++) though I'd like to put it stronger: although it doesn't make a difference in this particular case, List::MoreUtils::any is the only one that will work in general even when the value to search does not evaluate to boolean true.

This will not work:

print "@a\n" if List::Util::first { 0 == $_ } @a

This will:

print "@a\n" if List::MoreUtils::any { 0 == $_ } @a

If it wasn't for the difference that any returns a boolean "found" while first returns the actual element found, the two might as well be aliases to the same code.

grep in scalar context will work fine too but if the list is large it may be wasteful because it always goes through the whole list to return the number of matches even if it could stop after the first.

Replies are listed 'Best First'.
Re^3: If any element-in-array comparision
by repellent (Priest) on Jan 29, 2012 at 22:39 UTC
      This will not work:

      print "@a\n" if List::Util::first { 0 == $_ } @a

    When using first as a condition, it's best to wrap it in a defined() to specifically check for the 'not found' case:
    # this always works print "@a\n" if defined(List::Util::first { defined($_) && 0 == $_ } @ +a);

    OTOH, I agree that first clobbers the predicate when checking for undef -- i.e. we can't tell if we found undef:
    # doesn't work print "@a\n" if defined(List::Util::first { !defined($_) } @a);