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?

After the goto, not even caller() will be able to tell that this routine was called first.

So if you goto &{'debug'}; after you shitfed $self out, you'll "call" your debug subroutine seemlessly, as if you were there in the first place. Be careful about unshifting or shifting the $self argument into @_ when you do that.

As long as things after the bar(); call inside sub baz still get to run, I don’t mind. bar — in our case package OOModule; sub debug { ...; } — really only needs to invoke main::debug with a string somehow and doesn’t need to manipulate things afterwards. It seems that goto &{quack} is just about right for this.

There are two programs, in both debug is a fancy little debug message printer. In one of them, _debug is an actual sub that does a little more than this, it also sends the debug message to a server for central logging. In the other app, _debug is just an alias, so any case of _debug will still work: *_debug = \&debug;

Now, in the app that has the actual sub _debug { ... } declared, Perl will tell me ‘Ambiguous use of &{_debug} resolved to &_debug’, for a line which contains the following: goto &{_debug};