S
shanx
eval seems to be way too complicated for simple minded souls. I really
can't figure out what eval does behind the scenes even for some simple
things.
Here are a few samples:
1.
$a = "my $b = 10; print 'hi $b';";
eval $a;
Nothing happens. But if you change $a to
$a = 'my $b = 10; print "hi $b";'
... it works! You see the hi message now. Why is the quoting altering
eval's behavior? It's almost as if double quotes makes eval think that
the expression has already been evaluated.
2.
Excerpt from perldoc -f eval
"eval EXPR
EXPR is parsed and executed as if it were a little Perl program. It
is executed in the context of the current Perl program, so that any
variable settings or subroutine and format definitions remain
afterwards.
The value returned is the value of the last expression evaluated, or a
return statement may be used, just as with subroutines. The last
expression is evaluated in scalar or array context, depending on the
context of the eval."
Variable settings or subroutine definitions are supposed to remain
afterwards, but they remain only *sometimes*. Here is an example:
@tests = (
{
'cmd' => '$greeting = "hello";'
},
{
'cmd' => 'print "$greeting\n";'
}
);
foreach $i (@tests) {
eval $i->{cmd};
}
You would imagine that $greeting remains set for the second invocation,
but it doesn't.
-Shanker
can't figure out what eval does behind the scenes even for some simple
things.
Here are a few samples:
1.
$a = "my $b = 10; print 'hi $b';";
eval $a;
Nothing happens. But if you change $a to
$a = 'my $b = 10; print "hi $b";'
... it works! You see the hi message now. Why is the quoting altering
eval's behavior? It's almost as if double quotes makes eval think that
the expression has already been evaluated.
2.
Excerpt from perldoc -f eval
"eval EXPR
EXPR is parsed and executed as if it were a little Perl program. It
is executed in the context of the current Perl program, so that any
variable settings or subroutine and format definitions remain
afterwards.
The value returned is the value of the last expression evaluated, or a
return statement may be used, just as with subroutines. The last
expression is evaluated in scalar or array context, depending on the
context of the eval."
Variable settings or subroutine definitions are supposed to remain
afterwards, but they remain only *sometimes*. Here is an example:
@tests = (
{
'cmd' => '$greeting = "hello";'
},
{
'cmd' => 'print "$greeting\n";'
}
);
foreach $i (@tests) {
eval $i->{cmd};
}
You would imagine that $greeting remains set for the second invocation,
but it doesn't.
-Shanker