in reply to If any element-in-array comparision

When the problem description contains the word "any" in the context of a list of items, List::MoreUtils::any seems like an ideal fit.

use List::MoreUtils qw{ any }; print "@array\n" if any { $_ > 0.1 } @array;

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.


Dave

Replies are listed 'Best First'.
Re^2: If any element-in-array comparision
by mbethke (Hermit) on Jan 27, 2012 at 18:41 UTC
    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.

        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);