2.3.1. Behaviour of Functions inside Functions

One can define such a reference to a function within another function. It is possible that this reference will be made accessible to the outside world after the outer function has terminated. In that case, the the inner function (which is called a closure) will remember all the relevant variables of the outer function.

Note that if two calls were made to the outer function, then the two resulting closures are by no mean related. Thus, changes in the variables of one closure will not affect the other. (unless, of course, they are global to both).

Here's an example to illustrate this:

#!/usr/bin/env perl

use strict;
use warnings;

sub create_counter
{
    my $counter = 0;

    my $counter_func = sub {
        return ($counter++);
    };

    return $counter_func;
}

my @counters = (create_counter(), create_counter());

# Initialize the random number generator to a constant value;
srand(24);

for my $i (1 .. 100)
{
    # This call generates a random number that is either 0 or 1
    my $which_counter = int(rand(2));

    my $value = $counters[$which_counter]->();

    print "$which_counter = $value\n";
}

Written by Shlomi Fish