Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

Can caller() or the call stack be tricked?

by Ralesk (Pilgrim)
on Jul 08, 2013 at 11:41 UTC ( #1043094=perlquestion: print w/replies, xml ) Need Help??

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?

Replies are listed 'Best First'.
Re: Can caller() or the call stack be tricked?
by Eily (Monsignor) on Jul 08, 2013 at 13:03 UTC

    It looks like a job for goto

    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.

      Hah!, I knew I’d seen something like this before — thanks!

      Also, that manual is the most hilarious thing ever. “Create spaghetti code”.

      One of the reasons I love Perl is that it has quips like this throughout its documentation.

Re: Can caller() or the call stack be tricked?
by tobyink (Canon) on Jul 08, 2013 at 21:05 UTC

    As noted above a goto allows you to omit your sub from the call stack. There's a price to pay though; control flow never returns to your sub.

    use Carp qw(cluck); sub foo { cluck(1) }; sub bar { goto \&foo; carp "here" }; sub baz { bar() }; baz(); # bar() is not shown in the stack trace, # but "here" never gets carped!

    For more powerful call stack trickery there's Sub::Uplevel (pure Perl, but slows down all uses of caller in your application) and Scope::Upper (even more powerful).

    package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name

      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.

Re: Can caller() or the call stack be tricked?
by DrHyde (Prior) on Jul 10, 2013 at 13:29 UTC
Re: Can caller() or the call stack be tricked?
by Ralesk (Pilgrim) on Aug 06, 2013 at 12:14 UTC

    I used the recommended goto SUB way. Here’s what happens.

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

    What exactly might be so ambiguous about this?

    Relevant code pieces for easier understanding:

    package OO::SubModule; sub new { my ($class, $args) = @_; my $self = { ( defined $args ? %$args : () ) }; bless($self, $class); ## Some boilerplate debug callback that we can override during const +ruction $self->{debug_cb} //= sub { my $self = shift; carp("DEBUG ".join(", +", map { defined $_ ? $_ : "undef" } @_)); }; return $self; } sub _debug { my $self = $_[0]; goto &{$self->{debug_cb}}; } ## You can say $self->_debug("booya") to do $self->{debug_cb}->("booya +") without it ending up in the call stack
    ## both apps $oosub = OO::SubModule->new({ debug_cb => sub { my $self = shift; my ($str) = @_; goto &{_debug}; }, }); ## Any occurrence of $self->_debug("booya") within OO::SubModule reall +y does _debug("booya") of the main app, this way ## Without getting in the call stack, right?

      Sigh. Why did I use curlies in those gotos?

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1043094]
Front-paged by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (6)
As of 2019-10-16 01:54 GMT
Find Nodes?
    Voting Booth?