bessarabov
bessarabov

Reputation: 11871

Why does Perl thinks that `1 and 0` is true?

Here is the sample. For some strange reason Perl thinks that 1 and 0 is a true value. Why?

$ perl -e '$x = 1 and 0; print $x;'
1

Upvotes: 6

Views: 258

Answers (3)

Borodin
Borodin

Reputation: 126722

It doesn't:

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

Upvotes: 6

nandhp
nandhp

Reputation: 4817

Because the precedence of and and && differ:

$x = 1 and 0 is like ($x = 1) and 0, whereas $x = 1 && 0 is like $x = (1 && 0).

See perlop(1).

Upvotes: 12

mpapec
mpapec

Reputation: 50647

Operator precedence in your example is

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

while what you want is:

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

or

perl -e '$x = 1 && 0; print $x;'

Upvotes: 11

Related Questions