Hmm, state variables are in my view a useful addition to Perl, but not quite as useful as closure variables. They are also a bit counter-intuitive, as in the following example provided by the OP:
sub global_sum { state $sum = 0; $sum += $_[0]; $sum; }
If I don't know what state is doing, I might think that $sum is reset to 0 each time through the sub, and I get a totally wrong idea of what the sub is really doing. It is not really obvious that the first line in that sub is executed only the first time through the sub and not in the next calls. Also, consider this example:
$ perl -e ' > use strict; > use warnings; > use v5.10; > > sub somefunc > { > state $var = do { > say "Heavy calculations"; > 42+$_[0]; > }; > } > > say somefunc(0); > say somefunc(10); > ' Heavy calculations 42 42
Although it is quite easy to explain what is going on, I would submit that this can be unexpected. The following code, using a closure, is more along the line of the behavior you would probably want:
$ perl -e ' > use strict; > use warnings; > use v5.10; > { my $var = 42; > sub somefunc > { > $var + shift; > } > } > say somefunc(5); > say somefunc(10); > ' 47 52

In reply to Re: 'state' variables and unit testing by Laurent_R
in thread 'state' variables and unit testing by vsespb

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.