All entries

True and False

13 Oct 2013
Эта же задача по-русски: здесь.

One day a programmer heard that logic operators in Perl worked incorrectly and decided to see it for herself. She ran a one-liner:

> perl -le '$x = 1 and 0; print $x;'
1

Huh… True AND False equals True. How so?

Hint

Show

It’s nice to program in plain English: and, or, not

Hint-2

Show

How about this?

> perl -le '$x = 1 && 0; print $x;'

Hint-3

Show

Why have two duplicating operators: && and and?

Disclosure

Show

In Perl operators && and and have different precedence and the one-liners above differ in the order of evalution.

The second one is similar to C:

> perl -le '$x = (1 && 0); print $x;'

But the first program actually means:

> perl -le '($x = 1) and 0; print $x;'

Resume: operators and and or have low precedence and they are a bad fit for logical expressions. They are perfect for idioms such as @info = stat($file) or die;