Tuesday, February 17, 2009

Subroutine References

Subroutine references work somewhat like pointers to functions in C. As a consequence such references can be used to create sophisticated structures in your Perl programs. An example of such structures are:
  • Dispatch Tables - Data structures that are used to map events to subroutines references.
  • Higher-order procedures -- A higher-order procedure is one that is able to take other procedures as arguments.
  • Closures - A subroutine that packages it's own environment when created.
Subroutines can be named or anonymous. To create a "named" reference consider the following example:

sub sayHelloWorld {
    print "Hello World! \n";
}
$refToSub = \&sayHelloWorld; # Create a "named" reference to a subroutine

The following is an example of how to create an "anonymous" reference to a subroutine
$refToSub = sub {
    print "Hello World! \n";
};

When it is time to use the subroutine reference you must "dereference" the reference. An example of calling the subroutine indirectly with the reference follows:

&$refToSub(); # Call the sayHelloWorld subroutine indirectly

The arrow syntax -> can also be used as follows:

$refToSub->();