Beefy Boxes and Bandwidth Generously Provided by pair Networks Ovid
Just another Perl shrine

Re: Real life uses for closures.

by Dallaylaen (Scribe)
on Feb 12, 2013 at 09:32 UTC ( #1018322=note: print w/ replies, xml ) Need Help??

in reply to Real life uses for closures.

Event loop programming.

Ever written anything with Tk or AnyEvent? Both are almost useless without closures.

The app runs as follows: something happens in the outside world (e.g. socket receives data, or user pushes button, or timer fires), and a corresponding sub is called by the event loop engine. Such a sub is called a callback.

Of course, if you only expect two or three kinds of events, there's no need for closures. However, in a real world app one needs to create callbacks on the fly, without knowing beforehand what exacly they whould do. And closures rock.


PSGI allows returning a closure instead of immediate [200, [ header...], [body...]]. It's great if you want to answer to the user ASAP and then do some long-running stuff. Again, not useful for a hello world.

Scope guards

Suppose you need to free some resource after leaving a particular code section. One can surround the code with layers of eval's and rethrows. Or one can use a guard object (e.g. Guard) that does its work in DESTROY, no matter why it was destroyed. Very often the code passed to guard's constructor is a closure holding a reference to the resource in question.

And there are much more (class method generation, infinite sequences, etc) uses of closures. However, most of them require a rather large application/module surrounding them to prove truly useful, maybe that's why textbook examples don't look convincing.

A sub{ ... } can do, say, 95% of what string eval can, but is also perfectly controllable and predictable.

Comment on Re: Real life uses for closures.
Re^2: Real life uses for closures.
by LanX (Abbot) on Feb 12, 2013 at 11:40 UTC

    Good points, I agree with you about the use cases!

    Just your definition of closures seems to be reduced to just generating anonymous functions.

    That's not the point, the main characteristic of closures is accessing variables from the outer scope at definition/generation time, most efficiently even shared between multiple closure-functions.

    So a real-world example should include shared private variables.

    Cheers Rolf









Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1018322]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (16)
As of 2014-03-14 15:28 GMT
Find Nodes?
    Voting Booth?

    Have you used a cryptocurrency?

    Results (307 votes), past polls