Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't 2==4 return false?

Tags:

perl

I come from C++ background and am trying to learn perl with Beginning Perl. However, this code in the second chapter has 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? 

It is explained further below, that the value of 2==4 is undefined, but this seems confusing and counter-intuitive to me. Two obviously isn't equal to four and the same comparison between 4 and 4 would yield true, leading to a '1' at the end of the output. Why doesn't the expression return false?

like image 547
Worse_Username Avatar asked Dec 02 '22 18:12

Worse_Username


1 Answers

It does. However, Perl does not have true and false. It has true-ish and false-ish values.

Operators that return boolean values will return a 1 when true, and when false, a special value that is numerically zero and the empty string when stringified. I suggest you numify the result by adding zero:

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

Output:

Is two equal to four? 0
like image 75
amon Avatar answered Dec 10 '22 23:12

amon