There is some overlap in applicability, but the main semantic difference between
{ my $x = 42; my $s = sub { $x++ }; say &$s(); }
and
my $s = sub { state $x = 42; $x++ }; say &$s();
is that the former initializes $x before &$s is created, while the latter does not initialize $x until the first time you call &$s. Note also that with state each created anonymous sub gets its own copy of $x, since technically it's a different lexical scope (or a different pad for the same lexical scope, depending on how you look at it).

This makes little difference with the two snippets above, since in the first example the my also creates a new $x every time you execute the snippet, but if you created $x only once, and then created the closure multiple times in a loop, you'd notice that the single my $x is shared among them.

However, that difference is not why we introduced state variables. The big win is the psychological one of not having to look outside of the sub to find the definition of $x. (That, and we wanted it as a primitive in Perl 6 so that people could write stateful macro constructs without forcing the user to define the state variable externally; in fact, we also use it ourselves in order to implement the stateful flipflop operator without having to build the flipflop in as a primitive, as it is in Perl 5.)


In reply to Re: About "state" variables in Perl 5.10 by TimToady
in thread About "state" variables in Perl 5.10 by citromatik

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.