in reply to Re^3: Experimental features: autoderef vs postfix deref
in thread Experimental features: autoderef vs postfix deref
"... 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
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^5: Experimental features: autoderef vs postfix deref
by BrowserUk (Patriarch) on Jul 12, 2015 at 21:14 UTC | |
by kcott (Archbishop) on Jul 12, 2015 at 22:55 UTC | |
by BrowserUk (Patriarch) on Jul 12, 2015 at 23:13 UTC | |
by kcott (Archbishop) on Jul 13, 2015 at 13:52 UTC |