develooper Front page | perl.perl5.porters | Postings from October 2003

Re: [perl #24250] "return" required in some anonymous closures

Dave Mitchell
October 20, 2003 18:18
Re: [perl #24250] "return" required in some anonymous closures
Message ID:
On Tue, Oct 21, 2003 at 12:05:44AM +0100, Nicholas Clark wrote:
> On Mon, Oct 20, 2003 at 11:53:03PM +0100, Dave Mitchell wrote:
> > Thus, I like Elizabeth's suggestion of using a compile-time attribute
> > to explicitly turn on this special behaviour, and thus to not suprise the
> > ordinary user.
> I like it, but I'm worried that I may be hasty, so I'd like to to simmer
> for a bit more before committing anything half baked to maint.
> (Woohoo. Mixed metaphors. Flavour clash)

(Now 2am. Have had a bath. Should have quitted while ahead at 1am; instead
I'm going to throw an even more hare-brained idea out that I will regret
in the morning).

I provisonally propose the new syntax:

    sub foo() : constant { ...}
    sub() : constant { ...}

which has the effect of:

for a named sub: as soon as the sub is compiled, it is executed once in
scalar context, and the return value is used at the basis for a new
CONST CV which replaces the original CV.

ie roughly speaking

    sub foo() : constant { $x + $y }

is about equivalent to

    sub foo() { $x + $y }
    BEGIN {
	my $val = foo();
	no warnings 'redefine';
	eval 'sub foo() { "' . $val . "}'

For an anon sub, the execution is done each time the sub is cloned, ie

    $a = sub() : constant { $x + $y }

is about equivalent to 

    $a = sub() { $x + $y };
    my $val = $a->();
    $a = eval 'sub () { "' . $val . "}'

Of course we can optimise the common cases of {1} or {$x} like we do at the
moment, so we don't actually have to execute the sub then throw it away
to determine its value.

Having implemeted this, would would immediately throw away the
special sub(){$outer_lexical} behaviour, on the grounds that it
is horrible, is undocumented, and has only been around since 5.8.0.

More controversially, we might then want to deprecate the whole
"sub foo(){1} is a constant sub" syntax, on the grounds that it's
a none-intuitive hack; posssibly even with the warning 'use :constant

But I've never been any good at language design...

(Hey, we could roll it out in 5.8.2, and if the community likes it, we
could backport it into bleedperl....;-)

Technology is dominated by two types of people: those who understand what
they do not manage, and those who manage what they do not understand. Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About