"... and a new mechanism specifically designed to replace them that doesn't."

Firstly, I'm assuming that statement is based on the opening paragraph from "perlsub: Persistent Private Variables":

"There are two ways to build persistent private variables in Perl 5.10. First, you can simply use the state feature. Or, you can use closures, if you want to stay compatible with releases older than 5.10."

My interpretation of that, is that you can replace

{ my $closure; sub x1 { $closure = shift if @_; $closure } }

with the more succinct

sub x1 { state $closure; $closure = shift if @_; $closure }

[And similarly for: local our $closure;]

state variables are lexically scoped. If you declare two state variables (with the same name) in different scopes, e.g.

sub x1 { state $closure ... } sub x2 { state $closure ... }

they will remain different variables: changing one has no effect on the other.

The form you presented with "sub x1{ our $closure = ..." loses the benefits of lexical scoping. $closure is now just aliasing a package variable accessible globally. A quick and dirty example:

$ perl -le 'sub x { our $c = shift if @_; $c } $::c = 1; print for x() +, x(2)' 1 2

In closing, my assumption (stated initially) may be wrong; in which case, I'd be interested in the "specifically designed" part you mentioned. I do use state for purposes other than closures: typically, once-off initialization of variables used in a single subroutine (but that's, perhaps, getting a bit off-topic).

— Ken


In reply to Re^4: Experimental features: autoderef vs postfix deref by kcott
in thread Experimental features: autoderef vs postfix deref by stevieb

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.