Subroutines & signatures

State variables

Full

Per-closure persistent variables, initialised once and retained across calls.

A state variable lives inside a sub or block but keeps its value between calls. Its initialiser runs only the first time execution reaches it; after that the stored value persists.

Persistent counter #

sub counter {
    state $n = 0;
    return $n++;
}
say counter();
say counter();
say counter();
Output
0
1
2

state $n = 0 initialises $n once; each call returns then increments the retained value.

Accumulating across calls #

Because the initialiser is skipped after the first call, state is a clean way to accumulate.

my &f = { state $x = 0; $x += $_ };
say f(10);
say f(5);
Output
10
15

Notes #