4

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?

Mat
  • 202,337
  • 40
  • 393
  • 406
Worse_Username
  • 318
  • 1
  • 11

4 Answers4

12

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
amon
  • 57,091
  • 2
  • 89
  • 149
  • 1
    Don't forget to mention 0E0 that is not false event though it isnumerically 0 http://stackoverflow.com/questions/129945/what-does-0-but-true-mean-in-perl – teodozjan Aug 23 '13 at 10:21
  • 1
    @teodozjan The *string* `"0E0"` is numerically zero, but true. This is because truth is first determined by the string value, then by the numeric value. This quirk has little to do with the question, or my answer. – amon Aug 23 '13 at 10:25
  • IMHO it is worth mentioning for someone who is new to perl logic system. – teodozjan Aug 26 '13 at 15:14
5

One way to see how perl is evaluating this expresion is to apply the ternary operator. If the expression on the left side is true it will return the value after the question mark otherwise if the expression is False it will return the value after the colon.

use strict;
use warnings;

print "Is two equal to four? ", 2 == 4 ? 'True' : 'False', "\n";
#This print False.
edi_allen
  • 1,878
  • 1
  • 11
  • 8
1

Perl doesn't have true and false types, so the result of evaluating any kind of comparison can't be them. You get values that are equivalent instead.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Same goes for PHP:

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

will output the following:

[1][] 

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

Hope this helps :)

Greetings

Christopher

Christopher Stock
  • 1,399
  • 15
  • 18
  • In Perl the canonical false value has a numeric value (`0`) associated with it. Which prevents it from warning the first time you use it as a number. – Brad Gilbert Aug 24 '13 at 16:42