Hello Laurent_R,
I think you are correct: your example code does seem to fulfil the requirements for a closure according to the Wikipedia article Closure_(computer_programming). And at the start of the tutorial Closure on Closures, broquaint takes a similar view:
However, I believe this isn't entirely accurate as a closure in perl can be any subroutine referring to lexical variables in the surrounding lexical scopes.
But, as you point out, this type of closure isn’t very useful, since there is no way to change the value of $add from outside the block. And if we try to return a reference to a named function from within another function, it doesn’t work as required:
#! perl use strict; use warnings; use v5.14; sub make_add { my $addpiece = shift; sub add { my $c = shift; return ($c + $addpiece); } return \&add; } my $f1 = make_add(20); my $f2 = make_add(35); say $f1->(10); say $f2->(10);
Output:
2:40 >perl 1102_SoPW.pl Variable "$addpiece" will not stay shared at 1102_SoPW.pl line 9. 30 30 2:40 >
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
In reply to Re^3: closures: anonymous subs vs function templates?
by Athanasius
in thread closures: anonymous subs vs function templates?
by 5haun
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |