in reply to anonymous vs named subroutines as closures
Named subroutines have global visibility. They don't nest. When Perl compiles ask_monkey_about, there's no lexical named %usd in scope. Yes, the name exists and Perl knows about it, but Perl hasn't created the actual hash for ask_monkey_about to close over. That creation will only happen when something calls cookup2 and Perl actually executes my.
In the anonymous case, Perl creates the subroutine reference after it's run the my to create the lexical variable, which is the important difference.
Named subroutines can indeed close over lexicals:
{ my %usd; sub ask_monkey_about { # do something with %usd } }
... but named subroutines don't nest.
|
|---|