12.5.2 A Simple Example of A Closure

12.5.2  A Simple Example of A Closure

 The following example has an anonymous function and a set of bindings associated with it. Therefore, it is an example of a closure. Here is the code.

 Program 12.18

sub funcallS{
           my ($funRef, $parameter) = @_;
           &$funRef($parameter);
}

sub listAdd1{
    my ($n, @lst) = @_;

    my $addN = sub {
        my $x = $_[0];
        $x + $n;
    };

    map {funcallS ($addN, $_)} @lst;
};

@list = (1,2,3);
@newlist = listAdd1 (10, @list);

 

Let us focus on the function listAdd1. Inside listAdd1, we define a statically or lexically scoped variable $n which gets its value from the first parameter to the call to listAdd1. We also define another variable called @lst.

Next, we define an anonymous function that is referenced by the scalar $addN. Let us concentrate on this function now. The function defines a local, statically scoped variable $x and assigns a value to it. Next, it returns the sum $x + $n. However, $n is a variable that is not bound inside the anonymous function. The binding of $n comes from outside the anonymous function but from within listAdd1. Thus, here, we have an anonymous function and a binding that is external to it. This is an example of a closure.

Once the anonymous function is defined, the last statement in listAdd1 performs a map of the anonymous function on every element of the list variable lst.