Why doesn't 2 == 4 return false?

I come from C ++ and I'm trying to learn perl with Perl. However, this code in chapter two left me confused:

#!/usr/bin/perl use warnings; print"Is two equal to four? ", 2 == 4, "\n"; 

When I run the code, this is output:

 Is two equal to four? 

The following explains that the value 2 == 4 is undefined, but this seems confusing and contradictory to me. Two, obviously, are not equal to four, and the same comparison between 4 and 4 will give the truth, leading to "1" at the end of the output. Why doesn't the expression return false?

+4
source share
4 answers

This is true. However, Perl does not have true and false . It has the values ​​true-ish and false-ish.

Operators that return booleans return a 1 when true, and when false - a special value that is numerically zero and an empty string when scribing. I suggest you number the result by adding zero:

 use warnings; print"Is two equal to four? ", 0+(2 == 4), "\n"; 

Output:

 Is two equal to four? 0 
+12
source

One way to see how perl evaluates this expression is to use the ternary operator. If the expression on the left side is true, it will return the value after the question mark; otherwise, if the False expression returns the value after the colon.

 use strict; use warnings; print "Is two equal to four? ", 2 == 4 ? 'True' : 'False', "\n"; #This print False. 
+5
source

Perl has no true and false types, so the result of evaluating any comparison cannot be it. Instead, you get equivalent values.

+1
source

The same goes for PHP:

 echo "[" . ( 0 == 0 ) . "][" . ( 0 == 1 ) . "]"; 

will output the following:

 [1][] 

The boolean value TRUE is converted to the string "1". Boolean FALSE is converted to "" (empty string). This allows you to convert back and forth between boolean and string values.

Hope this helps :)

Hi

Christopher

0
source

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


All Articles