Bryan R Harris wrote:
Bryan R Harris wrote:
This is unintuitive:
perl -e 'print "> "; while(<>) {print(( eval $_ )[-1], "\n> ")}'
... then enter 2*012. It prints "20". 2*12 is obviously 24, but perl's
interpreting that "012" as octal. We sometimes have our numbers zero padded
to make the columns line up, they're not octal.
Is there any way to keep perl's eval from interpreting numbers starting with
"0" as octal?
I tried to regex them out but that regex is tricky since I'm writing a
custom calculator, and I have no idea what the user might enter.
$ perl -lne 'BEGIN{$\="\n> ";print}s/(\d+)/0+$1/eg;print+(eval)[-1]'
2*012
24
% perl -lne 'BEGIN{$\="\n> ";print}s/(\d+)/0+$1/eg;print+(eval)[-1]'
2*012
24
2*12.02
24.4
perl -lne 'BEGIN{$\="\n> ";print}s/(-?[\d.]+)/0+$1/eg;print+(eval)[-1]'
Oops, not perfect, but I have a feeling the answer is going to look
something like that.
"print+(eval)[-1]"??? What's the "+" for? You're amazing, John.
The "+" is so that you don't get a syntax error because "print(eval)"
with "[-1]" after it is nonsensical. BTW, why are you using a list
slice anyway? Won't "print eval" work just as well?
perl -lne 'BEGIN{$\="\n> ";print}s/(-?[\d.]+)/0+$1/eg;print eval'
John
--
The programmer is fighting against the two most
destructive forces in the universe: entropy and
human stupidity. -- Damian Conway
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/