Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will there be any difference between 42, 42.0, "42.0", "42"

Tags:

perl

During the process of testing my Perl code using "Smart Match(~~)" I have faced this problem. Will there be any difference between 42, 42.0, "42.0", "42"

$var1 = "42";
$var2 = "42.0";
$a = $var1 ~~ $var2;

I am getting $a as 0; which means $var1 and $var2 are not equal.

Please Explain.

like image 436
VAR121 Avatar asked Sep 25 '12 08:09

VAR121


1 Answers

The smart match operator will "usually do what you want". Please read this as "not always".

42 ~~ 42.0 returns true.

42 ~~ "42.0" returns true as well: the string is compared to a number, and therefore seen as a number. Ditto for "42" ~~ 42.0.

"42" ~~ "42.0" returns false: both arguments are strings, and these strings do not compare as "equal", although their numerical meaning would. You wouldn't want Perl to view "two" ~~ "two-point-oh" as true.

A string can be forced to it's numeric interpretation by adding zero:

0+"42" ~~ "42.0" returns true again, as the first string is forced to the number 42, and the second follows suit.

The perldoc perlsyn or perldoc perlop page defines how smart matching works:

       Object  Any       invokes ~~ overloading on $object, or falls back:
       Any     Num       numeric equality         $a == $b
       Num     numish[4] numeric equality         $a == $b
       undef   Any       undefined                !defined($b)
       Any     Any       string equality          $a eq $b

You can see that string equality is the default.

like image 179
amon Avatar answered Nov 15 '22 10:11

amon