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!


In reply to Callback Design by MeowChow

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.