diff options
author | Father Chrysostomos <sprout@cpan.org> | 2012-09-10 23:44:11 -0700 |
---|---|---|
committer | Father Chrysostomos <sprout@cpan.org> | 2012-09-15 22:45:10 -0700 |
commit | ad0cc46c82c89c5da407ee3163b95c03d5a31426 (patch) | |
tree | 2526bec8c01cf6a0fb29b5236ff95948f12c8f4a /pod/perlsub.pod | |
parent | a70c2d5688349e997aaf662f41f2dfe6a9b1fe27 (diff) | |
download | perl-ad0cc46c82c89c5da407ee3163b95c03d5a31426.tar.gz |
perlsub: Document state variables better
Diffstat (limited to 'pod/perlsub.pod')
-rw-r--r-- | pod/perlsub.pod | 15 |
1 files changed, 15 insertions, 0 deletions
diff --git a/pod/perlsub.pod b/pod/perlsub.pod index 54441a097f..2efd325f80 100644 --- a/pod/perlsub.pod +++ b/pod/perlsub.pod @@ -458,12 +458,27 @@ by using C<-E> on one-liners (see L<feature>). Beginning with Perl 5.16, the C<CORE::state> form does not require the C<feature> pragma. +The C<state> keyword creates a lexical variable (following the same scoping +rules as C<my>) that persists from one subroutine call to the next. If a +state variable resides inside an anonymous subroutine, then each copy of +the subroutine has its own copy of the state variable. However, the value +of the state variable will still persist between calls to the same copy of +the anonymous subroutine. (Don't forget that C<sub { ... }> creates a new +subroutine each time it is executed.) + 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 } +And this example uses anonymous subroutines to create separate counters: + + use feature 'state'; + sub create_counter { + return sub { state $x; return ++$x } + } + Also, since C<$x> is lexical, it can't be reached or modified by any Perl code outside. |