So, with a few calls, you can see an incremented count:
count_one( );
count_one( );
count_one( );
print "we have seen ", count_so_far( ), " coconuts!\n";
$count retains its value between calls to
count_one( ) or count_so_far(
), but no other section of code can access this
$count at all.
In C, this is known as a static local variable:
a variable that is visible to only a subset of the
program's subroutines but persists throughout the
life of the program, even between calls to those subroutines.
What if you wanted to count down? Something like this will do:
{
my $countdown = 10;
sub count_down { $countdown-- }
sub count_remaining { $countdown }
}
count_down( );
count_down( );
count_down( );
print "we're down to ", count_remaining( ), " coconuts!\n";
That is, it'll do as long as you put it near the
beginning of the program, before any invocations of
count_down( ) or count_remaining(
). Why?
This block doesn't work when you put it after those
invocations because there are two functional parts to the first line:
my $countdown = 10;