State variable lifecycle when subroutine invoked via goto &sub
0 reputation · 13 Feb 2020, 21:46 UTC
The goal is to determine the exact lifetime of a Perl 'state' variable when its containing subroutine is invoked repeatedly with 'goto &sub' instead of a normal call.
According to the documentation, a 'state' variable lives as long as the subroutine's symbol table remains loaded, and is freed when that symbol table is unloaded or the interpreter exits. However, 'goto &sub' replaces the caller's frame while leaving the callee's symbol table intact, so the associated state stash is not released during the program's execution.
This creates an unresolved decision: the language specification does not define whether the state stash should be considered eligible for reclamation while the subroutine remains in memory, nor does it provide an explicit way to reset or discard the variable in such a pattern.
Is the state stash eligible for garbage collection when the subroutine remains loaded but no further invocations occur via normal call?
Should developers treat state variables as effectively permanent when using 'goto &sub' in long-running loops, or is there a recommended practice to avoid unintended memory retention?