summaryrefslogtreecommitdiff
path: root/pod/perlsub.pod
diff options
context:
space:
mode:
authorRafael Garcia-Suarez <rgarciasuarez@gmail.com>2006-07-06 14:31:55 +0000
committerRafael Garcia-Suarez <rgarciasuarez@gmail.com>2006-07-06 14:31:55 +0000
commitba1f8e91c84952b3b5031787643c5e7b0bfa1fa8 (patch)
treece69e7500d9b40acbcc23bdd1332dcc93a21b219 /pod/perlsub.pod
parent834df1c59777570a74dbdc390d6beedbd3d1e56c (diff)
downloadperl-ba1f8e91c84952b3b5031787643c5e7b0bfa1fa8.tar.gz
Document state() variables in perlsub
p4raw-id: //depot/perl@28493
Diffstat (limited to 'pod/perlsub.pod')
-rw-r--r--pod/perlsub.pod45
1 files changed, 44 insertions, 1 deletions
diff --git a/pod/perlsub.pod b/pod/perlsub.pod
index 082d520d69..7a51e5cabb 100644
--- a/pod/perlsub.pod
+++ b/pod/perlsub.pod
@@ -431,7 +431,50 @@ L<perlref/"Function Templates"> for something of a work-around to
this.
=head2 Persistent Private Variables
-X<static> X<variable, persistent> X<variable, static> X<closure>
+X<state> X<state variable> X<static> X<variable, persistent> X<variable, static> X<closure>
+
+There are two ways to build persistent private variables in Perl 5.10.
+First, you can simply use the C<state> feature. Or, you can use closures,
+if you want to stay compatible with releases older than 5.10.
+
+=head3 Persistent variables via state()
+
+Beginning with perl 5.9.4, you can declare variables with the C<state>
+keyword in place of C<my>. For that to work, though, you must have
+enabled that feature beforehand, either by using the C<feature> pragma, or
+by using C<-E> on one-liners. (see L<feature>)
+
+For example, the following code maintains a private counter, incremented
+each time the gimme_another() function is called:
+
+ use feature 'state';
+ sub gimme_another { state $x; return ++$x }
+
+Also, since C<$x> is lexical, it can't be reached or modified by any Perl
+code outside.
+
+You can initialize state variables, and the assigment will be executed
+only once:
+
+ sub starts_from_42 { state $x = 42; return ++$x }
+
+You can also, as a syntactic shortcut, initialize more than one if they're
+all declared within the same state() clause:
+
+ state ($a, $b, $c) = ( 'one', 'two', 'three' );
+
+However, be warned that state variables declared as part of a list will
+get assigned each time the statement will be executed, since it will be
+considered as a regular list assigment, not one to be executed only once:
+
+ (state $x, my $y) = (1, 2); # $x gets reinitialized every time !
+
+B<Caveat>: the code at the right side of the assignment to a state
+variable will be executed every time; only the assignment is disabled. So,
+avoid code that has side-effects, or that is slow to execute. This might
+be optimized out in a future version of Perl.
+
+=head3 Persistent variables with closures
Just because a lexical variable is lexically (also called statically)
scoped to its enclosing block, C<eval>, or C<do> FILE, this doesn't mean that