Anno has asked for the wisdom of the Perl Monks concerning the following question:
That prints: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);
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.x: 0 x: 1 x: 1 x: 1 x: -undef- x: -undef-
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 | |
by Anno (Deacon) on Mar 11, 2007 at 10:54 UTC | |
by Anno (Deacon) on Mar 12, 2007 at 16:58 UTC |