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.
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.
In reply to Re: Real life uses for closures.
by Dallaylaen
in thread Real life uses for closures.
by BrowserUk
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |