Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Callback Design

by repson (Chaplain)
on Jan 16, 2001 at 08:43 UTC ( [id://52155]=note: print w/replies, xml ) Need Help??


in reply to Callback Design

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' }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://52155]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2024-04-25 10:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found