in reply to closure clarity, please

sub definitions are parsed once only. The closure retains the value it had at that point in time. Try this:

use warnings; use 5.010; for my $num (1 .. 5) { my $a = $num; {say "in block: $a"}; *test = sub { say "in function: $a"; }; test() } __END__ c:\test>junk11 in block: 1 in function: 1 in block: 2 Subroutine main::test redefined at C:\test\junk11.pl line 11. in function: 2 in block: 3 Subroutine main::test redefined at C:\test\junk11.pl line 11. in function: 3 in block: 4 Subroutine main::test redefined at C:\test\junk11.pl line 11. in function: 4 in block: 5 Subroutine main::test redefined at C:\test\junk11.pl line 11. in function: 5

You can disable the redefinition warning.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
RIP PCW It is as I've been saying!(Audio until 20090817)

Replies are listed 'Best First'.
Re^2: closure clarity, please
by ikegami (Patriarch) on Nov 24, 2009 at 07:10 UTC

    sub definitions are parsed once only. The closure retains the value it had at that point in time.

    Yes, subs are only parsed once, but that's irrelevant.

    The capturing occurs when the code ref is created. That's when the sub is defined for named subs, and that's when the sub op is executed for anonymous subs.

    Furthermore, closures capture variables, not values. The value of the variable can be changed, from both inside and outside the sub.

      Different words, same result.


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.

        Different results.

        According to what you said, the following should print "0" instead of "1":

        my $x; BEGIN { $x = 0 } my $f = sub { $x }; ++$x; print $f->();

        Let's say you didn't mean the above. According to what you said, the following should print "11" instead of "12":

        for (1..2) { my $x = $_; print sub { $x }->(); }