Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

State variables and recursion

by Anno (Deacon)
on Mar 10, 2007 at 16:05 UTC ( [id://604136] : perlquestion . print w/replies, xml ) Need Help??

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://604136]
Approved by Joost
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (3)
As of 2024-02-06 03:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found