On 8/15/05, Kripa Sundar <[EMAIL PROTECTED]> wrote:
> Dear Ben,
>
> > > > another bad point about eval is that it can access and modify lexicals
> > > > and globals anywhere in the code. so that can lead to action at a
> > > > distance and very hard to find bugs.
> > > [...]
> > I'm not sure if this is what is referred to, but it applies.
> >
> > If this is dynamic code where the string to be evaled is
> > passed in from elsewhere, then one problem is that you
> > might wind up picking up lexicals in the scope of the
> > eval, and being unable to pick up lexicals in the scope
> > where you tried to create the eval. Closures would get
> > this right.
> >
> > Ruby solves this problem by giving you a number of
> > variations on eval, one of which evals things in the
> > context of your caller. Still not perfectly general, but
> > much more likely to be right in this instance.
>
> Do you mean examples like below?
>
> ----------------------\/--------BEGIN---------\/----------------------
> % perl -le 'my $x = 7; my $str = q{print ++$x}; {my $x = 11; eval $str}'
> 12
> %
> ----------------------/\---------END----------/\----------------------
Close, but I meant more like this:
sub foo {
my $x = 7;
my $generator = make_generator(q{++$x}};
print $generator->() for 1..5;
}
sub make_generator {
my $action = shift;
my $x = 11;
eval qq{
sub {
# Some interesting code here...
$action;
}
};
}
> IMHO the current behaviour is intuitive. And I certainly don't
> see "action at a distance". The person who thinks that the '$x' inside
> $str is referring to the currently visible $x (value 7) is simply
> mistaken. Likewise the person who thinks that the inner $x will remain
> untouched by the eval(). (But maybe this latter is what Uri is
> referring to as "action at a distance".)
I agree that Perl's behaviour is logical. However it is
inconvenient. And from the point of the person who is
trying to use make_generator, it causes internal details
to matter too much.
A workaround, of course, is to tell the person to use
global variables. Which works except for the variables
that happen to be used internally in make_generator,
which the person doing the calling should not need to
know but does.
Cheers,
Ben
_______________________________________________
Boston-pm mailing list
[email protected]
http://mail.pm.org/mailman/listinfo/boston-pm