- publishing free software manuals
Perl Language Reference Manual
by Larry Wall and others
Paperback (6"x9"), 724 pages
ISBN 9781906966027
RRP £29.95 ($39.95)

Sales of this book support The Perl Foundation! Get a printed copy>>>

8.2.1 Persistent variables via state()

Beginning with perl 5.9.4, you can declare variables with the state keyword in place of my. For that to work, though, you must have enabled that feature beforehand, either by using the feature pragma, or by using -E on one-liners. (see "Perl pragma to enable new features" (feature) in the Perl Library Reference Manual (Volume 1))

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 $x is lexical, it can't be reached or modified by any Perl code outside.

When combined with variable declaration, simple scalar assignment to state variables (as in state $x = 42) is executed only the first time. When such statements are evaluated subsequent times, the assignment is ignored. The behavior of this sort of assignment to non-scalar variables is undefined.

ISBN 9781906966027Perl Language Reference ManualSee the print edition