From: Paul Johnson <[EMAIL PROTECTED]>
> On Sun, Jan 19, 2003 at 06:44:31PM +0100, Jacques Lederer wrote:
> > When you write
> >
> > $calc=3+5-2;
> > print $calc."\n";
> >
> > you get 6. (number, not the string "3+5-2")
> >
> > When you write
> >
> > while (<STDIN>) {
> > $calc=$_;
> > print $calc."\n";
> > last;
> > }
> >
> > if you run that last one and type 3+5-2, you get 3+5-2.(string
> > "3+5-2", not the number 6)
> >
> > Why is it so? And how can I get it to calculate the thing?
>
> The input you get is a string. If you want to treat it as a Perl
> expression you need C<eval>.
>
> $calc = eval;
>
> This does what you want, plus a lot more.
>
> Be careful not to type "unlink <*>" for example.
I guess that if you only want to evaluate some basic math there it'll
be easiest to do this:
$calc = <STDIN>;
# remove everything except numbers, dots, +, -, *, / and ( )
$calc =~ tr{0-9+\-*/.() }{}dc;
$result = eval $calc;
die "Incorrect expression: $calc\n\t$@\n"
if $@;
print "Result: $result\n";
If you want to warn the user that the expression contained something
you did not want you can do this:
$calc = <STDIN>;
# we have to strip the newline at the end of the entered data!
chomp($calc);
# remove everything except numbers, dots, +, -, *, / and ( )
if ($calc =~ tr{0-9+\-*/.() }{}dc) {
die "You can only enter numbers, +, -, *, /, ., ( and )\n";
}
$result = eval $calc;
die "Incorrect expression: $calc\n\t$@\n"
if $@;
print "Result: $result\n";
HTH, Jenda
===== [EMAIL PROTECTED] === http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]