bug in perl with prefixed 0 numbers

  • A+
Category:Languages

when I try to execute the following(01434.210 instead of 1434.210)

$val=22749.220-(21315.010+01434.210) print $val 

I get these output

output 638.207900000001 

But according to me output must be 0.

What am I missing?

 


A leading 0 in a literal number makes Perl interpret the value I'm base 8:

 123   # 123, in decimal 0123   # 123 in octal, but 83 in decimal 

This isn't the same for strings converted to numbers. In those Perl ignores the leading 0s. The string-to-number conversion only deals in base-10:

 "123" + 0   # 123 "0123" + 0   # still 123 

In your example in the comment, you convert a literal number to a string with a leading zero. When you convert that string back to its numeric form you get the same value you started with:

$val=sprintf("%05d",1434);   # converting 1434 to the string "01434" print $val; print "/n";      # still a string print $val+21315;            # "01434" + 21315 => 1434 + 21315 print "/n";  print 01434+21315;           # oct(1434) + 21315 => 796 + 21315 

The leading zero notation helps with certain builtins that typically use octal numbers, such as those that deal with unix permissions:

chmod 0644, @files 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: