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


in reply to Re: Re: Callback Design
in thread Callback Design

Hmm. Let me see if I understand: you want to be able to do something like grep or map, where your code gets passed a subref which you then call back?

If so, you don't need to worry about changing packages at the time you call it, since it will have already picked up the proper package when it was defined (and compiled) in the caller's code:

package my; $global = 'in_my'; sub own_map(&@) { my $code = shift; my @return = (); push @return, $code->() for @_; @return; } package main; $global = 'in_main'; print my::own_map { $_, " ", $global, "\n" } (1..20); # prints "1 in_main\n", "2 in_main\n" and so on
In the above code, my::own_map could have molested ${ (caller)[0] . "::global" } to pass a value in to the block. I guess this might be OK (although it's clearly an abuse of caller, which AFAIK was intended for debugging), as long as it's well documented and you are careful to localize everything.

Updated: removed a confusing and unneeded $_ argument on the line that calls the callback. Oops!