Perl 5.10 added a new class of variables ‘state’ that are similar to ‘my’ in scope but are only initialized once. Even inside of a subroutine a state variable will only be initialized on the first call to the subroutine and will maintain it’s last value between calls. A simple example is the easiest way to show how state works. In the code below the two subroutines are identical except that the variable $countval is declared with my in the first sub (non_state_count) and with state in the second sub (state_count). This means the $countval variable will be initialized on every call to non_state_count and will not maintain it’s value between calls. In state_count it’s the opposite and $countval will initialize only once and then maintain it’s last value between calls.
#! /usr/bin/perl
use feature qw(state);
print "Result of calls to non_state_count\n";
for ($i = 0; $i < 10; $i++) {
print non_state_count() . ' ';
}
print "\n notice that the variable countval is reinitialized on every call\n";
print "Result of calls to state_count\n";
for ($i = 0; $i < 10; $i++) {
print state_count() . ' ';
}
print "\n observe that the variable countval now retains its value between calls\n";
sub non_state_count {
my $countval;
return ++$countval;
}
sub state_count {
state $countval;
return ++$countval;
}
You should see the output of the script as:
|
Result of calls to non_state_count 1 1 1 1 1 1 1 1 1 1 notice that the variable countval is reinitialized on every call |
Result of calls to state_count 1 2 3 4 5 6 7 8 9 10 observe that the variable countval now retains its value between calls |