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

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

From:
Dave Mitchell
Date:
October 20, 2003 03:46
Subject:
Re: [perl #24250] "return" required in some anonymous closures
Message ID:
20031020104539.GA2952@fdgroup.com
On Mon, Oct 20, 2003 at 12:17:24PM +0200, Elizabeth Mattijsen wrote:
> (I should stop answering my own posts  ;-)
> 
> At 11:55 +0200 10/20/03, Elizabeth Mattijsen wrote:
> >Hmmm... both of the following return correct results also:
> 
> The problem can be simplified to the following code:
> 
> my $foo = 'foo';
> my $get = sub () {$foo};
> my $set = sub ($) {$foo = $_[0]};
> $set->('bar');
> print "foo = $foo = ".$get->()."\n";
> __END__
> foo = bar = foo
> 
> 
> so this looks like an optimizer problem to me: the $get sub is 
> referring to something else than the package lexical $foo.


This isn't a bug, it's a feature :-)

sub () {$lexical} is a constant sub generator, ie each call to 'sub'
returns a new constant sub rather than a closure. It doesn't seem to be
well documented though. Been around since 5.8.0.

eg

    my $x;

    for (10,20) {
	$x = $_;
	$a0 = sub(){$x};
	$a1 = sub(){$x+1};
	print $a0->(), " ", $a1->(), "\n";
	$x += 1000;
	print $a0->(), " ", $a1->(), "\n";
    }

outputs

    10 11
    10 1011
    20 21
    20 1021

since $a0 is a constant sub, but $a1 is a closure.


-- 
print+qq&$}$"$/$s$,$*${$}$g$s$@$.$q$,$:$.$q$^$,$@$*$~$;$.$q$m&if+map{m,^\d{0\,},,${$::{$'}}=chr($"+=$&||1)}q&10m22,42}6:17*2~2.3@3;^2$g3q/s"&=~m*\d\*.*g



nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About