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
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.