Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

boolean

perl

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
like image 292
bessarabov Avatar asked Oct 11 '13 19:10

bessarabov


People also ask

Is 0 true or false in Perl?

False Values: Empty string or string contains single digit 0 or undef value and zero are considered as the false values in perl.

Does Perl have objects True or false?

Unlike many other languages which support object orientation, Perl does not provide any special syntax for constructing an object. Objects are merely Perl data structures (hashes, arrays, scalars, filehandles, etc.)

Does Perl have booleans?

Perl does not have a special boolean type and yet, in the documentation of Perl you can often see that a function returns a "Boolean" value. Sometimes the documentation says the function returns true or returns false.


3 Answers

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

like image 100
nandhp Avatar answered Oct 18 '22 07:10

nandhp


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;'
like image 38
mpapec Avatar answered Oct 18 '22 08:10

mpapec


It doesn't:

$ perl -e '$x = (1 and 0); print $x;'
0
like image 39
Borodin Avatar answered Oct 18 '22 07:10

Borodin