12.5.3 Closures That Share A Scalar Variable
12.5.3 Closures That Share A Scalar Variable
Closures defined inside one function can share a variable. We have three such closures defined inside the counter function in the code below. They all share the value of the scalar variable $counter that is defined as a local variable inside counter.
Program 12.19
sub counter{
my $counter = 0;
sub returnCounter{
$counter
}
sub incrCounter{
$counter++
}
sub resetCounter{
$counter = 0;
}
}
counter;
incrCounter;
#prints 1
printf "\$counter = %d\n", returnCounter;
incrCounter; incrCounter; incrCounter;
#prints 4
printf "\$counter = %d\n", returnCounter;
incrCounter; incrCounter; incrCounter;
#prints 7
printf "\$counter = %d\n", returnCounter;
resetCounter; incrCounter; incrCounter;
#prints 2
printf "\$counter = %d\n", returnCounter;
Here, inside counter, we first declare $counter to be a local variable and set it to 0. Then, we define three functions returnCounter, incrCounter and resetCounter that return the current value, increment the current value and reset the value of the $counter variable which is local and inaccessible from outside counter. Since the three functions inside counter are defined with names, the names are visible outside the body of counter.
So, by calling these three functions we can access and manipulate the value of $counter which is inaccessible outside counter. The calls to the three functions outside counter show what effect these function calls have.
