Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re^2: If any element-in-array comparision

by mbethke (Hermit)
on Jan 27, 2012 at 18:41 UTC ( [id://950430]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://950430]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2024-04-19 19:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found