The problem is that all coderefs work like closures. When a piece of code is complied the the variable $foo in it, it will not store the name $foo, but rather the current position in the parse tree that $foo would refer to in normal usage. When this piece of compiled code is passed into a subroutine in any package it isn't changed, so the place that said $foo still refers to the variable which was complied into the code.

The map, sort and grep callbacks use the variables $_, $a and $b which are special cases, where their usage always refers to the same position in the parse tree (though that can be displaced with local, but we won't go into that).

On the other hand callbacks for modules such as HTML::Parser and Tk are passed a full list in @_ (using $code_ref->('foo',3,'blah');) which means those callbacks generally begin with my($foo,$blah)=@_; to extract that data.

In your case I'd say your best bet may be to stick to using $_, something like this.

$_ = 'hi'; my $code = sub { print $_->{blah} . "\t" . $_->{moo} . "\n" }; Bar::hi($code); print $_ . "\n"; # prints 'hi' package Bar; sub hi { my $coderef = shift; local $_ = { 'foo' => 2, 'blah' => 5, 'moo' => 'blah' }; &$coderef; # prints '5 blah' }

In reply to Re: Callback Design by repson
in thread 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.