...
This noncompliant code example improperly uses eq
to test two numbers for equality. Counterintuitively, this code prints false.
Code Block | ||||
---|---|---|---|---|
| ||||
my $num = 02; # ... 2; print "Enter a number\n"; my $user_num = <STDIN>; chomp $user_num; if ($num eq "02"$user_num) {print "true\n"} else {print "false\n"}; |
This code will print true
if the user enters 2
, but false
if the user enters 02
,The counterintuitive result arises because $num
is interpreted as a number. When it is initialized, the 02
string is converted to its numeric representation, which is 2
. When it is compared, it is converted back to a string, but this time it has the value 2
, so the string comparison fails.
Compliant Solution (Numbers)
This compliant solution uses ==
, which interprets its arguments as numbers. This code therefore prints true
even though if the right argument to ==
is explicitly provided as a stringinitialized to some different string like 02
.
Code Block | ||||
---|---|---|---|---|
| ||||
my $num = 02; # ...2; print "Enter a number\n"; my $user_num = <STDIN>; chomp $user_num; if ($num == "02"eq $user_num) {print "true\n"} else {print "false\n"}; |
...