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

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

From:
Yitzchak Scott-Thoennes
Date:
October 20, 2003 12:19
Subject:
Re: [perl #24250] "return" required in some anonymous closures
Message ID:
20031020191628.GA3056@efn.org
On Sun, Oct 19, 2003 at 11:01:42PM -0000, "martin@suttles.sca.sfbay.sun.com (via RT)" <perlbug-followup@perl.org> wrote:
> my $count = 0;
> my $x = [sub() { $count },
> 	 sub() { return $count },
> 	 sub($) { $count += $_[0] }];
> $x->[2](3);
> printf "%d %d\n", $x->[0](), $x->[1]();
> 
> This prints
> 0 3
> when it should print
> 3 3
> 
> The two anonymous subs $x->[0] and $x->[1] should
> have exactly the same effect because `return' is
> supposed to be redundant when returning the last
> expression in a sub.

This surprising behaviour is intentional.  See perlsub/Constant
Functions.  The doc there could use some improvement to mention
anonymous subs.  (Note that constant.pm relies on this behaviour.)

Actually, there does seem to be a bug here.  If you reverse the order
of the first two subs, $count should have an extra refcnt that should
prevent the constant sub, but it doesn't work that way.  This seems to
be fixed in bleadperl.



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