http://qs1969.pair.com?node_id=52096

MeowChow has asked for the wisdom of the Perl Monks concerning the following question:

This is actually a two-part question:

1. Can Perl be coaxed into calling an anonymous sub as if the sub were in a package than it's own? For example:

package Foo; my $coderef = sub { $global }; $global = 'in Foo'; package Bar; $global = 'in Bar'; print &$coderef;
This code prints 'in Foo', but I would like a way of getting it to print 'in Bar'.

I don't want to go the route of defining code as a string for eval and then prepending a package line to the code string... things would be much cleaner if I could use anonymous sub refs instead.

2. Callback routines for this module should be defined as anonymous subs, ideally mimmicking the way map, grep, and sort work (except, of course, that a sub would be needed before the code block). The user of the module should not have to include code to set a bunch of parameters from @_ when they write their callbacks, as I want callbacks to be lean and simple. Ideally, I want parameters pre-prepared in a "throw-away" package that their subs would get called in (as above), but if that won't work, I'm considering the possibility of callbacks getting their parameters prepared in a hash referenced by a localized $_ (for example $$_{name}). Are there any pitfalls or drawbacks to doing things this way. Which would you consider the most "perlish" way to accomplish my goals?

Thanks monks!