in reply to Re^2: closures: anonymous subs vs function templates?
in thread closures: anonymous subs vs function templates?
Hello Laurent_R,
You understood me correctly, and it appears I was wrong: you have shown that it is possible to build a closure using function templates. But I note that, to get the syntax to work, you had to remove the local from the definition of *inner within sub make_adder, and that makes *inner a package global sub. In fact, what sub make_adder returns is simply the string *main::inner. So we can dispense with make_adder’s return value and the assignments to *f1 and *f2 altogether:
#! perl use strict; use warnings; use v5.14; make_adder(20); say inner(10); make_adder(25); say inner(10); sub make_adder { my $addpiece = shift; print "\$addpiece = $addpiece\n"; *inner = sub { return shift() + $addpiece; }; }
Output:
13:02 >perl 1102_SoPW.pl $addpiece = 20 30 $addpiece = 25 Subroutine main::inner redefined at 1102_SoPW.pl line 15. 35 13:02 >
This approach is inferior to the standard technique (references to anonymous subroutines) in at least two ways:
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: closures: anonymous subs vs function templates?
by 5haun (Scribe) on Dec 22, 2014 at 04:10 UTC | |
|
Re^4: closures: anonymous subs vs function templates?
by Laurent_R (Canon) on Dec 22, 2014 at 07:56 UTC |