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);


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

Fork me on GitHub
  • http://poisonbit.wordpress.com poisonbit

    There is a really nice book (freely available), on the topic of Perl and FUNctional style, by Mark Jason Dominus:

    Higher-Order Perl (http://hop.perl.plover.com/book/)

    I really liked it, and in case you haven’t read it, and like the topic, I can just recommend to take a read. For me it was an enlightening experience.

    Greetings

    • http://ppant.blogspot.com ppant

      Thanks Arrondo (a.k.a. poisonbit) for valuable info. I am still reading it covered few chapers only but really wants to finish. The book is really an eye opener and gives all together new dimension of thinking. Kudos to Mark.

  • http://khatar.phear.org marc chantreux

    https://github.com/eiro/p5-lazyness really helps you to manipulate that kind of stuff. i’ll release it on CPAN soon.

    hth

    regards