taji01 taji01 - 1 month ago 17
Perl Question

Compare variables with leading zero in perl

I'm trying to compare the first 7 characters in $num1 and $num2. When i compile it i get a weird output. The output doesn't match $num1 or $num2. How can i compare these 2 variables?


OUTPUT: num1[2739073] num2[2739074]


$num1 = 012345601;
$num2 = 012345602;

#$num1 =~ s/^0+//;
#$num2 =~ s/^0+//;

if (substr($num1, 0, -2) == substr($num2, 0, -2)) {
print "num1[$num1]" . " num2[$num2]\n";
} else {
print "Not equal\n";
}

Answer

Issue #1:

In Perl you compare strings with the eq operator, not ==:

A correct comparison would be:

if ( substr($num1, 0, 7) eq substr($num2, 0, 7) ) {
    # ...
}
else {
    # ...
}

Issue #2:

Numbers that start with 0 in are interpreted as octal, you can read more about this in perldoc perlnumber

12345601 (octal) == 2739073 (decimal)
12345602 (octal) == 2739074 (decimal)

Issue #3:

Missing use strict; and use warnings;