In general, a
closure is a
function taken together with an
environment. Closures are applicable in languages which:
A closure has the
lexical environment of the point where it was created, no matter where it is called from.
The important bit in eric+'s program above is the `my' on the second line, which makes $whom a lexically-scoped variable. If it were changed to `local' (which introduces a new binding of a dynamically-scoped variable), the calls `&$a("World")' and `&$b("La Monde")' would produce warnings because no variable named `$salutation' would be in scope when they were called.
Closures are common in functional languages; Perl is such a mongrel that it could be considered a functional language. An example (in Scheme) paralleling eric+'s example above is:
(define (greet salutation)
(lambda (whom) (display (string-append salutation " " whom "\n"))))
(define a (greet "Hello"))
(define b (greet "Bonjour"))
(a "World") ; prints "Hello World\n"
(b "la Monde") ; prints "Bonjour la Monde\n"
Closures are often implemented as
thunks which know the
address of the
function, as well as that of its
activation record. Also common are `
fat pointers', which are
wide enough to contain the addresses of both the function and its activation record.