FAQ
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

Search Discussions

  • Yuval Kogman at Aug 14, 2006 at 4:44 pm

    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 <nothingmuch@woobling.org>
    http://nothingmuch.woobling.org 0xEBD27418
  • Jonathan Scott Duff at Aug 14, 2006 at 5:59 pm

    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
    duff@pobox.com

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupperl6-language @
categoriesperl
postedAug 14, '06 at 4:01p
activeAug 14, '06 at 5:59p
posts3
users3
websiteperl6.org

People

Translate

site design / logo © 2021 Grokbase