Clovis_Sangrail has asked for the wisdom of the Perl Monks concerning the following question:
It is troubling when you encounter what look like contradictions between divine(?) authority and observed behavior. I'm reading the original (2003) Alpaca book, learning of closures. Quoting page 73:
"A subroutine doesn't have to be an anonymous subroutine to be a closure. If a named subroutine accesses lexical variables and those variables go out of scope, the named subroutine retains a reference to the lexicals, just as you saw with anonymous subroutines."
OK, great, because I'd like to write the "ask_monkey_about" subroutine referred to in chapter 7 as a closure defined in a subroutine, and pass usage data into a lexical variable in that enclosing subroutine. (I want to try out this 'Schwartzian Transform' thingy.)
But I find that my "ask_monkey_about" named subroutine:
sub cookup2 { my %usd = @_; sub ask_monkey_about { my $cst = shift; $usd{$cst}; }; }
generates the ominous-sounding warning:
Variable "%usd" will not stay shared at t15.pl line 11.
The warning goes away if I instead define an anonymous subroutine within the enclosing subroutine. I did both, and ran it, and both versions seem to work:
$ cat t15.pl use strict; use warnings; my @usages = qw( Gilligan 23 Thurston 70 Lovey 98 ); my $ask; sub cookup2 { my %usd = @_; # Better be even #. sub ask_monkey_about { my $cst = shift; $usd{$cst}; }; } sub cookup { my %usd = @_; # Better be even #. return sub { my $cst = shift; $usd{$cst}; }; } $ask = cookup ( @usages ); print $ask->("Lovey") . "\n"; cookup2 ( @usages ); print ask_monkey_about("Lovey") . "\n";
$/opt/perl5.16/bin/perl t15.pl Variable "%usd" will not stay shared at t15.pl line 11. 98 98 $
Both work, but I still get that warning. Maybe the interpreter is just telling me that %usd is not accessible outside of the cookup2 block? Or are there circumstances where my use of the "ask_monkey_about" subroutine will fail in some way?
Maybe this is an evolving behavior in Perl? Is this one of the reasons why there are versions two and three of the alpaca book?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: anonymous vs named subroutines as closures
by chromatic (Archbishop) on May 31, 2013 at 19:46 UTC | |
|
Re: anonymous vs named subroutines as closures
by choroba (Cardinal) on May 31, 2013 at 19:45 UTC | |
|
Re: anonymous vs named subroutines as closures
by LanX (Saint) on May 31, 2013 at 20:44 UTC | |
|
Re: anonymous vs named subroutines as closures
by ikegami (Patriarch) on Jun 04, 2013 at 04:16 UTC | |
|
Re: anonymous vs named subroutines as closures
by Clovis_Sangrail (Beadle) on Jun 03, 2013 at 15:46 UTC |