Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: understanding closures

by blokhead (Monsignor)
on Sep 23, 2005 at 12:36 UTC ( #494502=note: print w/replies, xml ) Need Help??


in reply to understanding closures

The anonymous form of sub { ... } is like a dynamic subroutine constructor. Every time you get to the statement
return sub {$count++}
the Perl interpreter generates a new sub. It also happens to bundle up any lexical variables that the sub uses, which you seem to understand.

The my $var statement is also like a dynamic variable constructor. Every time you get to a my declaration, a brand new variable is created. Since you construct the closure inside this sub:

sub count_maker { my $count = shift;
So every time you call count_maker, a brand new $count variable is created and bundled up in the brand new anonymous sub closure. Then we leave the scope of count_maker, so that version of $count disappears other than its reference in the anonymous sub that is still around.

There are several things different about your other example. First, the non-anonymous form of sub name { ... } works a little differently. It generates a new sub at compile time, not at runtime when the statement is reached. That's why you can call a named sub that is defined lower down in the file. Also, you have two different $count variables in different scopes. The counter sub is always pointing to the one defined inside the do {} block, not the one in the calling scope. Also, the $count variable that is actually referenced in the sub is never redeclared (the do {} block is never entered more than once).

Here's another example that might be enlightening:

{ my $count1; ## only one copy of $count1 ever created, so ## it's shared by all closures created below sub count_maker { my $count2 = shift; ## $count2 is a different var each time ## each time we enter count_maker return sub { ($count2++, $count1++) } } } my $c1 = count_maker(1); my $c2 = count_maker(5); print join " ", $c1->(), $/; print join " ", $c2->(), $/; print join " ", $c2->(), $/; print join " ", $c1->(), $/; print join " ", $c1->(), $/; __OUTPUT__ 1 0 5 1 6 2 2 3 3 4

blokhead

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (11)
As of 2019-12-11 17:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?