Syntactic Confectionery Delight | |
PerlMonks |
Re: understanding closuresby blokhead (Monsignor) |
on Sep 23, 2005 at 12:36 UTC ( [id://494502]=note: print w/replies, xml ) | Need Help?? |
The anonymous form of sub { ... } is like a dynamic subroutine constructor. Every time you get to the statement
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: 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:
blokhead
In Section
Seekers of Perl Wisdom
|
|