Perl for Newbies - Part 3 - Modules and ObjectsReferences to FunctionsDynamic References to Functions

2.3. Dynamic References to Functions

It is possible to define a dynamic reference to a function. The code of its function is written as part of the assignment expression and can see all the variables in the scope in which it was defined. Here's an example:


use strict;
use warnings;
my $increment;

    my $counter;
    # The definition of a dynamic reference to function comes inside
    # a "sub {" ... "}" closure
    $increment = sub {
        print $counter, "\n";
        return $counter++;

while ($increment->() < 100)
    # Do Nothing

Written by Shlomi Fish