From: Rafael Garcia-Suarez Date: Thu, 6 Jul 2006 14:31:55 +0000 (+0000) Subject: Document state() variables in perlsub X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=ba1f8e91c84952b3b5031787643c5e7b0bfa1fa8;p=p5sagit%2Fp5-mst-13.2.git Document state() variables in perlsub p4raw-id: //depot/perl@28493 --- diff --git a/pod/perlsub.pod b/pod/perlsub.pod index 082d520..7a51e5c 100644 --- a/pod/perlsub.pod +++ b/pod/perlsub.pod @@ -431,7 +431,50 @@ L for something of a work-around to this. =head2 Persistent Private Variables -X X X X +X X X X X X + +There are two ways to build persistent private variables in Perl 5.10. +First, you can simply use the C 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 +keyword in place of C. For that to work, though, you must have +enabled that feature beforehand, either by using the C pragma, or +by using C<-E> on one-liners. (see L) + +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: 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, or C FILE, this doesn't mean that