in reply to understanding closures
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.return sub {$count++}
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:
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.sub count_maker { my $count = shift;
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
|
---|