Perl 5.32 state keyword: recursion persistence ambiguity
0 reputation · 10 Nov 2021, 13:30 UTC
In Perl 5.32 the state keyword is documented to create a lexical variable that retains its value across all calls to the enclosing subroutine, including recursive invocations. However, tests have shown that a state variable defined inside a recursive subroutine may reset to its initial value on each recursive layer. This discrepancy raises a question about the actual runtime behavior and its impact on performance when state is used to cache expensive computations in recursion.
The goal is to determine whether the state variable truly persists across recursive calls in Perl 5.32, and if not, how this affects both correctness and execution time. Constraints include the documented specification, the observed behavior in recent Perl releases, and the lack of a definitive bug report clarifying the issue.
Specific questions:
- How does a
statevariable behave when accessed in deep recursive calls in Perl 5.32? - Does the observed reset of
statevariables introduce measurable performance penalties compared to a plain lexical variable? - What best‑practice guidance exists for avoiding subtle bugs when using
statein recursive algorithms?