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?


In reply to Can caller() or the call stack be tricked? by Ralesk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.