ealeon
ealeon

Reputation: 12452

perl nested unless statements not equal to use of &&'s?

  7 foreach (@crons) {
  8     unless (index($_, "cks") != -1) {
  9         unless (index($_, "aab") != -1) {
 10             unless (index($_, "lam") != -1) {
 11                 push (@found, $_);
 12             }
 13         }
 14     }
 15 }

how come the above does not give the same output as the following:

  7 foreach (@crons) {
  8     unless (index($_, "cks") != -1 && index($_, "aab") != -1 && index($_, "lam") != -1) {
  9         push (@found, $_);
 10     }
 11 }

@crons has the list of strings and I am trying to get all string that does not have "cks", "aab" and "lam"

The first section of code does what i want but the second doesnt and in my mind, it should...
Can anyone care to explain why they are not the same nor why it does not give the same output?

Upvotes: 6

Views: 394

Answers (2)

Zaid
Zaid

Reputation: 37136

The non-equivalence of the two logics become clear when you test the string 'cks'.

The first logic would evaluate to false, the second would evaluate to true, since it does not contain the string 'aab' or 'lam'.

Upvotes: 1

amon
amon

Reputation: 57600

Let's call your conditions A, B, C. We now have the code

unless (A) {
  unless (B) {
    unless (C) {

The unless can be very confusing, so we write it only using if:

if (!A) {
  if (!B) {
    if (!C) {

Now we && those conditions together:

if (!A && !B && !C) {

This could also be written as

if (not(A || B || C)) {

This equivalence is called de Morgan's law

Upvotes: 11

Related Questions