State variables

A variable in a sub may be declared using the state keyword instead of my. In this case it will be created and initialized once, and its value will be saved between subsequent calls of that function.

sub cnt() {
    state $c = 0;

    return $c++;

say cnt(); # 0
say cnt(); # 1
say cnt(); # 2

The state variable still remains lexically scoped, and thus is not accessible outside of the block where it was defined.

With the state variables, the example demonstrated in the "Lexical variables" section, will not work: there will exist only one instance of the variable:

sub seq($init) {
    state $c = $init;

    return {$c++};

my $a = seq(1);
my $b = seq(42);

say $a(); # 1
say $a(); # 2
say $b(); # 3
say $a(); # 4
say $b(); # 5