Here's how to write a counter:
{
my $counter;
sub next_counter { return ++$counter }
}
Each time next_counter is called, it increments
and returns the $counter variable. The first time
next_counter is called,
$counter is undefined, so it behaves as though it
were 0 for the ++. The variable is not part of
next_counter's scope, but rather part of the block
surrounding it. No code from outside can change
$counter except by calling
next_counter.
Generally, you should use an INIT for the extra scope. Otherwise, you
could call the function before its variables were initialized.
INIT {
my $counter = 42;
sub next_counter { return ++$counter }
sub prev_counter { return --$counter }
}
This technique creates the Perl equivalent of C's static variables.
Actually, it's a little better: rather than being limited to just one
function, both functions share their private variable.