MeowChow has asked for the wisdom of the Perl Monks concerning the following 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:
This code prints 'in Foo', but I would like a way of getting it to print 'in Bar'.package Foo; my $coderef = sub { $global }; $global = 'in Foo'; package Bar; $global = 'in Bar'; print &$coderef;
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!
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Callback Design
by saucepan (Scribe) on Jan 16, 2001 at 04:34 UTC | |
by MeowChow (Vicar) on Jan 16, 2001 at 04:47 UTC | |
by saucepan (Scribe) on Jan 16, 2001 at 05:10 UTC | |
by MeowChow (Vicar) on Jan 16, 2001 at 05:34 UTC | |
by saucepan (Scribe) on Jan 16, 2001 at 06:46 UTC | |
| |
(Ovid warning: bad code ahead) Re: Callback Design
by Ovid (Cardinal) on Jan 16, 2001 at 06:08 UTC | |
Re: Callback Design
by repson (Chaplain) on Jan 16, 2001 at 08:43 UTC |