mjp
mjp

Reputation: 207

simple nested conditional statement in perl

I think I'm missing something, as I would say the below should print MATCH.

($one,$two)=(220,219);
print "MATCH" if (($one or $one+1 or $one-1) == ($two or $two+1 or $two-1));

Can't find an easy explanation why I don't see MATCH printed. Is there another way to simply test for the above condition?

Upvotes: 0

Views: 71

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89629

You test doesn't work because each parenthesis return always the first true assertion (i.e. the value of $one for the first and the value of $two for the second)

You can try something like this:

print "MATCH" if (abs($one-$two)<3)

Note: this works only with integers.

Upvotes: 2

Hunter McMillen
Hunter McMillen

Reputation: 61540

Logical or (e.g or) is a short-circuiting operator which means that in a statement like

A or B

B will only be evaluated if A is FALSE.

In your statement above:

($one or $one+1 or $one-1)

The value contained in the variable $one is TRUE (because it is != 0) so the value of $one is returned, which is 220.

($two or $two+1 or $two-1)

The value contained in the variable $two is TRUE (because it is != 0) so the value of $two is returned, which is 219.

220 == 219 is FALSE, so "MATCH" is not printed.

Upvotes: 3

Related Questions