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.
The smart match operator will “usually do what you want”. Please read this as “not always”.
42 ~~ 42.0returns 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 number42, and the second follows suit.The
perldoc perlsynorperldoc perloppage defines how smart matching works:You can see that string equality is the default.