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