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:
[code lang=”perl”]
$cref = &func;
[/code]
Reference to anonymous functions
[code lang=”perl”]
$cref = sub { … };
[/code]

To call a code reference:

Using a postfix arrow notation for dereferencing a code reference.

[code lang=”perl”]
@returned = $cref->(@arguments);
[/code]
A way to call the subroutine by reference prior to Perl 5.004
[code lang=”perl”]
@returned = &$cref(@arguments);
[/code]
Explanation:

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