Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

  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?

like image 988
ealeon Avatar asked Mar 05 '14 16:03

ealeon


2 Answers

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

like image 186
amon Avatar answered Nov 10 '22 13:11

amon


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'.

like image 30
Zaid Avatar answered Nov 10 '22 12:11

Zaid