http://www.perlmonks.org?node_id=1043094

Ralesk has asked for the wisdom of the Perl Monks concerning the following question:

Fellow Monks,

We have defined a debug function somewhere in our code, it does a few more things besides printing to the terminal — which is why I wouldn’t want to reimplement it outside of the main program. As far as displaying debug information goes, it prints, among other things, line numbers and calling sub names (two levels even). To achieve this, we use caller().

It works fine, but we’d like to pass it “deeper”, eg. to an OO module — so the module won’t have to know about anything (network connections where the debug function sends logs, etc.), it can just call the function and things will get done.

I thought the good idea for this would be to say something along the lines of $obj->{debug_cb} = sub { my $self = shift; my ($msg) = @_; debug($msg); }; around when I initialise the object. Of course, caller() gets into trouble because the call stack has now one level more than it should (and we’ll be printing __ANON__ due to the anon sub). If, in the OO module, I also define a sub debug { my $self = shift; my ($msg) = @_; $self->{debug_cb}->($msg); } so I don't have to write squiggles and arrows so much inside the OO module, the call stack will be shifted by two.

Is there another way to inject this function(ality) into a module and still get the right thing from caller(), something that tricks the call stack somehow?