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

The state feature in Perl 5.9+ doesn't seem to work right in recursive functions. Instead of holding the previous value, a state variable comes up undefined in recursive calls. The sub foo()below shows the value of a state variable $x in recursive and non-recursive calls:
use feature 'state'; sub foo { my $n = shift; state $x = 0; print "x: ", $x // '-undef-', "\n"; $x = 1; foo( $n - 1) if $n; } foo(0); foo(0); foo(0); print "\n"; foo(2);
That prints:
x: 0 x: 1 x: 1 x: 1 x: -undef- x: -undef-
The output is as expected except for the last two lines, which come from recursive calls. I woud have expected to see $x: 1 there too. The undefined value is certainly surprizing.

Is there a reasonable explanation? I think it's a bug.

Anno

Replies are listed 'Best First'.
Re: State variables and recursion
by TimToady (Parson) on Mar 11, 2007 at 05:01 UTC
    Yes, it's a bug. State variables should only replicate on closure cloning.
      Right, reported as #41789.

      Update: Ticket number added

      Anno

        ...and fixed in bleadperl. That was fast.

        Anno