Persistent Lexically Scoped Variables: state
A state variable is a lexically scoped variable, just like my. The only difference is that state variables will never be
reinitialized, unlike my
variables that are reinitialized each time their enclosing block is
entered. This is usually so that a function can have a private
variable that retains its old value between calls to that
function.
state variables are enabled
only when the use feature "state"
pragma is in effect. This will be automatically included if you ask
to use a version of Perl that’s
v5.10 or later:
use v5.14;
sub next_count {
state $counter = 0; # first time through, only
return ++$counter;
}Unlike my variables,
state variables are currently
restricted to scalars; they cannot be arrays or hashes. This may
sound like a bigger restriction than it actually is, because you can
always store a reference to an array or hash in a state variable:
use v5.14;
state $bag = { };
state $vector = [ ];
...
unless ($bag–>{$item}) { $bag–>{$item} = 1 }
...
push @$vector, $item;Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access