Clear questions and runnable code
get the best and fastest answer
anonymous vs named subroutines as closuresby Clovis_Sangrail (Beadle)
|on May 31, 2013 at 19:24 UTC||Need Help??|
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:
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:
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?