Why does Perl think that "1 and 0" are true?

Here is an example. For some strange reason, Perl thinks 1 and 0 are the true value. Why?

 $ perl -e '$x = 1 and 0; print $x;' 1 
+6
source share
3 answers

Since the priority of and and && is different:

$x = 1 and 0 is similar to ($x = 1) and 0 , while $x = 1 && 0 is similar to $x = (1 && 0) .

See perlop (1) .

+12
source

In your example, operator priority

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

while you want:

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

or

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

No:

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

Source: https://habr.com/ru/post/955803/


All Articles