Problems? Is your data what you think it is? | |
PerlMonks |
Re: Check multiple array elements for a single conditionby afoken (Chancellor) |
on Aug 26, 2016 at 06:51 UTC ( [id://1170516]=note: print w/replies, xml ) | Need Help?? |
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:
Or a little bit more perlish:
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". ;-)
In Section
Seekers of Perl Wisdom
|
|