12.5 Closures

12.5  Closures

  Before we get into the discussion on closures, let us first note that Perl allows us to define functions inside functions. When a function is defined inside a function, the function can be named or anonymous. An anonymous function is one that does not have a name and is referenced with a scalar reference variable. It is possible that an anonymous function, whether inside another function or not, refers to a variable that is not bound inside the anonymous function, but bound outside. In the case of a closure, the system saves copies of the bindings of such externally bound variables at the time the function is defined. Such a combination of an anonymous function and a set of variable bindings is called a closure. Closures are useful in a variety of applications.