develooper Front page | perl.perl6.language | Postings from June 2005

Re: How much do we close over?

Thread Previous | Thread Next
Dave Mitchell
June 12, 2005 16:24
Re: How much do we close over?
Message ID:
On Sun, Jun 12, 2005 at 11:26:49PM +0100, Piers Cawley wrote:
> Chip and I have been having a discussion. I want to write:
>     sub foo { my $x = 1; return sub { eval $^codestring } }
>     say foo()("$x");
> I claim that that should print 1. Chip claims it should throw a warning
> about because of timely destruction. My claim is that a closure should
> close over the entire lexical stack, and not simply those things it uses
> statically. Chip claims the opposite, arguing that timely destruction
> implies that this is absolutely the right thing to do. It's also
> quicker.

I'm with Chip on this one. In fact, year ago I specifically fixed
bleedperl so that it gives this runtime warning:

$ perl592 -we 'sub f { my $x; sub { eval q($x)} } f()->()'
Variable "$x" is not available at (eval 1) line 2.

> But dammit, I'm doing runtime evaluation of code strings, I don't care about
> quicker.

You may be using slow evals, but other fast code may not be. Should the
closure in

     sub foo { my $x = 1; return sub { 1 } }

also capture the current instance of $x? You are basically condeming any
code that creates any closure, however simple, to basically hang on to
just about any data that has ever existed, in the vague hope that maybe,
just maybe, some day some code may use an eval and make use of that data.

> If it's not the default can it please be mandated that there be some way of
> doing:
>     sub foo { my $x = 1; return sub is lexically_greedy {eval $^codestring} }
> in other words, some way of declaring that a subroutine wants to hang onto
> every lexical it can see in its lexical stack, not matter what static analysis
> may say.

I have no opinion on that.

This is a great day for France!
    -- Nixon at Charles De Gaulle's funeral

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About