in reply to Re: Check multiple array elements for a single condition
in thread Check multiple array elements for a single condition
add the element number to the array slice, and update the equal-to count number.
Whenever a single change requires two (or more) synchronised updates to the code, this is a bug waiting to happen.
In this case, we can take advantage of the fact that “all x are y” is logically equivalent to “it is not the case that any x is not y.” That is, we can eliminate the duplication by negating both the condition and the if statement:
use strict; use warnings; my @array = qw( 0 0 7 abc 0 ); for my $i ([0, 1, 4], [0, 1, 3, 4], [1], [], [2]) { print "(@array[ @$i ]): "; if (grep !/^0$/, @array[ @$i ]) # !/^0$/ would be better as $_ ne + '0' { print "not all are zero\n"; } else { print "all are zero\n"; } }
Output:
1:40 >perl 1692_SoPW.pl (0 0 0): all are zero (0 0 abc 0): not all are zero (0): all are zero (): all are zero (7): not all are zero 1:40 >
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|