Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Curious corner cases concerning closure cloning

5 views
Skip to first unread message

Luke Palmer

unread,
Aug 14, 2006, 12:01:47 PM8/14/06
to perl6-l...@perl.org
What do these do?

for 1,2 {
my $code = {
my $x;
BEGIN { $x = 42 }
$x;
};
say $code();
}

for 1,2 {
my $code = {
state $x;
BEGIN { $x = 42 } # mind you, not FIRST
$x++;
};
say $code();
say $code();
}

for 1,2 -> $x {
END { say $x }
}

Thanks,
Luke

Yuval Kogman

unread,
Aug 14, 2006, 12:43:56 PM8/14/06
to Luke Palmer, perl6-l...@perl.org
On Mon, Aug 14, 2006 at 16:01:47 +0000, Luke Palmer wrote:
> What do these do?

Intuition based answers:

> for 1,2 {
> my $code = {
> my $x;
> BEGIN { $x = 42 }
> $x;
> };
> say $code();
> }

I think the closure would be emitted equivalently to my $x = 42, or
perhaps $x is not in the BEGIN blocks scope at all.

> for 1,2 {
> my $code = {
> state $x;
> BEGIN { $x = 42 } # mind you, not FIRST
> $x++;
> };
> say $code();
> say $code();
> }

Again, assuming the BEGIN { } body is not even compile but it's side
effect is meaningful, this is the same as

state $x = 42;

but starting to get a little tougher to justify.

Perhaps it does that, but also emits a warning e.g. 'implicit
initial value for future-scoped lexical' or something like that.


> for 1,2 -> $x {
> END { say $x }
> }

undef, because END is like a declaration putting the closure in some
global, and doesn't actually happen at runtime.

Otoh

for 1,2 -> $x {
state $y = $x;
END { say $y }
}

Might work

--
Yuval Kogman <nothi...@woobling.org>
http://nothingmuch.woobling.org 0xEBD27418

Jonathan Scott Duff

unread,
Aug 14, 2006, 1:59:15 PM8/14/06
to Luke Palmer, perl6-l...@perl.org
On Mon, Aug 14, 2006 at 04:01:47PM +0000, Luke Palmer wrote:
> What do these do?
>
> for 1,2 {
> my $code = {
> my $x;
> BEGIN { $x = 42 }
> $x;
> };
> say $code();
> }

Assuming that variables are available immediately as
they are parsed and that BEGIN blocks disappear as soon as they
execute, I'd expect that the first $code would be equivalent to

my $code = { my $x = 42; $x; };

and the second code would be equivalent to

my $code = { my $x ; $x; };

So, I guess the output would be

42
# this line intentionally left blank :-)


> for 1,2 {
> my $code = {
> state $x;
> BEGIN { $x = 42 } # mind you, not FIRST
> $x++;
> };
> say $code();
> say $code();
> }

Same thing here, except because it's a state variable, it keeps it's
value between invocations, so the output would be:

42
43
# again, blank on purpose
1

> for 1,2 -> $x {
> END { say $x }
> }

For this one I'd guess that a solitary "2" is output. The END block
closed over the $x and the last value that $x obtained was 2.

my humble guesses,

-Scott
--
Jonathan Scott Duff
du...@pobox.com

0 new messages