in reply to Check multiple array elements for a single condition

Another example using grep. This one isn't much shorter, but where it'll help is if you have to check more elements; simply add the element number to the array slice, and update the equal-to count number.

if ((grep /^0$/, @array[0,1]) == 2){ say "both are zero"; }

Replies are listed 'Best First'.
Re^2: Check multiple array elements for a single condition
by Athanasius (Archbishop) on Sep 11, 2016 at 15:41 UTC
    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,