The main difference I see is that the initialization of state variables only happens when the function is called. Consider:

use feature qw( :5.10 ); sub uncalled_sub { state $huge = huge_data_structure(); return; } print 'mem usage: ', my_mem(), "\n"; sub huge_data_structure { return [ ( 'x' x 1_000 ) x 100_000 ]; } sub my_mem { my ($proc_info) = grep { $_->[2] == $$ } map { [ split ] } `ps l | tail -n +2` +; return $proc_info->[6]; } __END__ mem usage: 11220

Compare to:

{ my $huge = huge_data_structure(); sub uncalled_sub { # state $huge = huge_data_structure(); return; } } print 'mem usage: ', my_mem(), "\n"; __END__ mem usage: 116132

Both tests were performed with Perl 5.10.0. You get the same kind of side effect (with time instead of memory) if initialization is a long_arduous_task().

Consider also:

print counter(), "\n"; { my $count = 0; sub counter { $count++ } } print counter(), "\n"; __END__ 0 0

Compare to:

use feature qw( :5.10 ); print counter(), "\n"; sub counter { state $count = 0; return $count++; } print counter(), "\n"; __END__ 0 1

Under ordinary circumstances, you won't notice either problem. Your initialization is fast, and it happens inside something you used, not in the middle of your program.

I think it also helps maintainability. You have the variable that's relevant to the function inside it instead of outside it. Even if they're right next to each other (as you have them), they could get separated later, and you don't want one of them left behind in some refactoring.


In reply to Re: About "state" variables in Perl 5.10 by kyle
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.