jeffguy,
Ok, there are a few things to keep in mind here. The first is that named sub declarations are scoped to the current package. The only way to have a lexical sub is for it to be an anonymous code ref. The second thing to keep in mind is that program flow never returns to a point above the sub declaration to even attempt to redefine the sub - it is a naked block.
If this doesn't answer your question, ask something a bit more specific. Better yet, play around and see if you can figure it out for yourself.
| [reply] |
I'm with you now. When I first looked at your code, I was thinking it was a chunk to be embedded in a subroutine, a la
sub test{
{
my $cnt = 1;
sub get_count {
return $cnt++;
}
}
print get_count();
}
print "test 4: ".test(4)."\n";
print "test 7: ".test(7)."\n";
so I was seeing get_count() should be defined repeatedly.
As you point out, since it is named, it is defined only once.
*Your* code shows the much more obvious and clear way of doing it -- define get_count() in a block outside any code.
Your explanations and examples were very helpful. Thanks a bunch!
| [reply] [d/l] |
But my intuition (which is apparently incorrect) says that sub get_count is redefined each time executing this block
No, named subs are only created once, during compilation. Anonymous subs are created each time you ask for one to be created. The lexical capture happens at creation time.
Dave.
| [reply] |