Hello 5haun,
As Laurent_R says, neither of your two inner functions is a closure. From the Glossary:
closure
An anonymous subroutine that, when a reference to it is generated at runtime, keeps track of the identities of externally visible lexical variables, even after those lexical variables have supposedly gone out of scope.
In both your examples, the inner subroutine references the lexical variable $y, but that is never out of scope. A better example is given in the perlfaq7 entry, “What’s a closure?”:
use strict; use warnings; my $f1 = make_adder( 20); my $f2 = make_adder(555); printf "%d\n", $f1->(10); printf "%d\n", $f2->(10); sub make_adder { my $addpiece = shift; print "\$addpiece = $addpiece\n"; my $inner = sub { return shift() + $addpiece; }; return $inner; }
Output:
22:42 >perl 1102_SoPW.pl $addpiece = 20 $addpiece = 555 30 565 22:42 >
It is apparent that the $inner sub is constructed when sub make_adder is called, but not run until called explicitly via the returned function pointer. But if we attempt to do this with a function template, the warning we get:
Use of uninitialized value in addition (+) at...
shows that the inner sub is actually run at the time when the outer sub is called.
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
In reply to Re: closures: anonymous subs vs function templates?
by Athanasius
in thread closures: anonymous subs vs function templates?
by 5haun
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |