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