Help:Why does eval add a 1 behind evaluations?

T

Tay Ray Chuan

Hi, I tried using eval like this:

print "Enter something to evaluate:\n";
while (defined($s = <>)) {
$result = eval $s;
if ($@) {
print "Invalid string:\n $s";
} else {
print "$result\n";
}
}

this can evaluate anything. but when I type this:

"$a=5;$b=5;$c=$a+$b;print $c;", it prints "101".

Why is there an extra "1"?
 
T

Tore Aursand

Tay said:
print "Enter something to evaluate:\n";
while (defined($s = <>)) {
$result = eval $s;
if ($@) {
print "Invalid string:\n $s";
} else {
print "$result\n";
}
}

this can evaluate anything. but when I type this:
"$a=5;$b=5;$c=$a+$b;print $c;", it prints "101".

Why is there an extra "1"?

You really should have read 'perldoc -f eval';

"[...] In both forms, the value returned is the value of the
last expression evaluated inside the mini-program [...]"

In other words: 'print $c;' returns 1.
 
J

Joe Smith

Hi, I tried using eval like this:

print "Enter something to evaluate:\n";
while (defined($s = <>)) {
$result = eval $s;
if ($@) {
print "Invalid string:\n $s";
} else {
print "$result\n";
}
}

this can evaluate anything. but when I type this:

"$a=5;$b=5;$c=$a+$b;print $c;", it prints "101".

Why is there an extra "1"?

Change
print "$result\n";
to
print "The result from eval() is $result\n";
and it will show what is really happening.
-Joe
 
T

Tad McClellan

Tay Ray Chuan said:
Hi, I tried using eval like this:

print "Enter something to evaluate:\n";
while (defined($s = <>)) {
$result = eval $s;
if ($@) {
print "Invalid string:\n $s";
} else {
print "$result\n";
}
}

this can evaluate anything. but when I type this:

"$a=5;$b=5;$c=$a+$b;print $c;", it prints "101".

Why is there an extra "1"?


The last expression eval()uated is the value of the eval(), so
$result gets print()'s return value (1).

So, the

print $c

outputs the 10

then

print "$result\n";

outputs the 1 and a newline.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top