Perltrap
Horror stories about Perl programmer. With hints and solutions.
Home
About
Authors
Why?
rss
@perltrapcom
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?
It’s nice to program in plain English: and
, or
, not
…
How about this?
> perl -le '$x = 1 && 0; print $x;'
Why have two duplicating operators: &&
and and
?
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;