Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re^2: Check multiple array elements for a single condition

by Athanasius (Archbishop)
on Sep 11, 2016 at 15:41 UTC ( [id://1171551]=note: print w/replies, xml ) Need Help??


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,

Log In?
Username:
Password:

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

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

    No recent polls found