Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re^2: closure clarity, please

by ikegami (Pope)
on Nov 24, 2009 at 07:10 UTC ( #809014=note: print w/ replies, xml ) Need Help??


in reply to Re: closure clarity, please
in thread closure clarity, please

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.


Comment on Re^2: closure clarity, please
Download Code
Re^3: closure clarity, please
by BrowserUk (Pope) on Nov 24, 2009 at 07:27 UTC

    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 }->(); }

        As JadeNB put it:

        * I'm intentionally being a bit sloppy here: as ikegami mentions, closures close over variables, not values; but, as the warning that you quote mentions, the actual variable that is closed over will no longer be accessible at the end of the subroutine invocation, so that there is no further way to change its value.

        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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://809014]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (6)
As of 2014-07-13 21:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (252 votes), past polls