Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Check multiple array elements for a single condition

by afoken (Chancellor)
on Aug 26, 2016 at 06:51 UTC ( [id://1170516]=note: print w/replies, xml ) Need Help??


in reply to Check multiple array elements for a single condition

Generalised for arrays of any size:

Checking if all elements of an array (all operator) match the same condition is equivalent to checking if at least one element (any operator) does not match the negated condition (De Morgan's laws).

grep can be used as an any operator, by checking the size of the returned array.

In code:

if (!grep { $_ != 0 } @array) { print "No array element is non-zero, so:\n"; print "All array elements are zero, or the array is empty\n"; }

Or a little bit more perlish:

unless (grep { $_ != 0 } @array) { print "No array element is non-zero, so:\n"; print "All array elements are zero, or the array is empty\n"; }

Note that grep is less efficient in this case than a specialised any function, because grep always tests the entire array, whereas the any function can stop at the first match. Both List::Util and List::MoreUtils offer an optimized any function.

Those modules also offer an optimized all function that stops after the first mismatch. They also offer the negated functions none and notall, and the function one that searches for exactly one match.


Could we patch Perl to implement grep as any (i.e. stop at the first match) if grep is used in a boolean context? Probably, but it would break code that abuses grep for its side effects, i.e. code that expects grep to always evaluate the block/expression for all array elements.

Alexander

--
Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2024-04-18 18:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found