http://www.perlmonks.org?node_id=176143

BrowserUk has asked for the wisdom of the Perl Monks concerning the following question:

The other day I was writing a recursive subroutine in which I wanted the sub to know the current depth of recursion.

In C, I would have used a local static - asking here in the CB, a kind fellow monk (sorry, I forgot which monk!) gave me the hint to use a 'my $variable' outside of the sub, but inside an enclosing anonymous block.

{ #(1) my $depth = -1; sub recurse { #(2) ++$depth; print +(" .") x $depth . "current depth:$depth\n" ; recurse() if $depth < 3; print +(" .") x $depth . "current depth:$depth\n" ; --$depth; } #(3) } #(4) recurse(); # (5)
The above (trivial) example produces:
current depth:0 .current depth:1 . .current depth:2 . . .current depth:3 . . .current depth:3 . .current depth:2 .current depth:1 current depth:0

Which is great. Exactly what I wanted. The only problem now is - I don't understand HOW it works.?

My (possibly flawed) conceptual understanding is that the sub keyword creates a named (or unnamed in the case of anonymous subs) block of code. That is to say, an entry in a symbol table somewhere with a "key" of "recurse" (in this case) and a value of the address where the compiler stored the code between the opening "{" (2) and its matching "}" (3). And when the label "recurse" is encountered (in the proper context), the label is looked up in the symbol table, the address of the code obtained and invoked.

To my (still very green) concept of these things, when the program is interpreted/complied/run, the my $depth var should come in to being at the top of the enclosing block (1) and disappear at the bottom (4). Meaning it wouldn't exist at the by the time the sub is invoked at (5)?

Anyone care to attempt to explain how this works to me<super>*</super> without reference to perlguts?


<super>*</super>Someone who has read the docs on my and local several times including the space-time explanation and is still somewhat confused.