Functional Programming in Perl: Part 2

* Closures

Lets take a look on closures:-

Need of closures:

Since closures are subroutine references with a bit of private data thrown in, they are very convenient to use as callback procedures in graphical user interfaces. There is a nice example which explains the need of using closures. This commonly used approach is called “smart” callback procedure.

For more info you can read chap 4 of Advanced Perl Programming by Sriram Srinivasan.

Functional Programming in Perl: Part 1

As we know  functional programming involves creating and manipulating functions to build up larger programs. This requires a language that allows functions to be used as input and return data to other functions. Perl has two important features that make it possible: –

* Code references

* Closures

Lets take code reference first:-

Need of code reference:

Sometimes we need to manipulate a subroutine by reference so we need to take the references to functions. This might happen if you need to create a signal handler, a Tk callback, or a hash of function pointers etc.

To get a code reference:

$cref = &func;

Reference to anonymous functions

$cref = sub { ... };

To call a code reference:

Using a postfix arrow notation for dereferencing a code reference.

@returned = $cref->(@arguments);

A way to call the subroutine by reference prior to Perl 5.004

@returned = &$cref(@arguments);


If the name of a function is func, you can produce a reference to this code by preceding that name with & . You can also create anonymous functions using the sub {} notation. These code references can be stored just like any other reference. So we can say that code references are same as function pointers in C and C++ and which certainly helps to improve coding.

In my next post I will try to cover closures.

Thanks for reading.

Ref: Perl Cookbook by Tom Christiansen & Nathan Torkingston