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.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With