in reply to Leading Zeros confound eval() ?

016 is an octal number

Replies are listed 'Best First'.
Re^2: Leading Zeros confound eval() ?
by misterperl (Friar) on Jul 21, 2015 at 19:04 UTC
    thanks guys - I thought about OCTAL. But why does eval() treat the val as octal, but outside of eval() its decimal? Why are they different? Larry had a bad day? I can't think of a reason why Perl should work this way.

      misterperl:

      In your original code, you have:

      my $x = "016";

      If you leave the quotes out, it would be treated as an octal number. So in the perl source code 016 is an octal number. But when perl converts a string to a number, it doesn't perform any octal, binary or hexadecimal conversions. So this bit of code would treat it as a normal decimal number:

      $ perl -e 'my $x="016"+1; print $x,"\n"' 17 $

      When you use eval, you can treat a string as a bit of perl source code, so it will be treated as an octal number:

      $ perl -e 'my $x=eval "016"; print $x,"\n"' 14 $

      Update: I should've read the rest of the thread before replying, Anonymonk already said this.

      ...roboticus

      When your only tool is a hammer, all problems look like your thumb.

      In your test without eval, you executed $x * 10

      In your test with eval, you executed 016 * 10

      You got different results because you executed different code, not because you used eval. If you had executed the same code with the eval as without (e.g. if you had used eval( '$x * 10' )), you would have gotten the same result.