What's so inefficient about it? The fact that there appears to be a lot of make-work code? I think you'll find that there are already modules available which will do what you want, Devel::StackTrace and Devel::CallerItem spring to mind, but I suspect they call caller under the covers themselves.

You could use them as building blocks, and then there wouldn't be as much visible caller-frame-grovelling code in your own code.

Or you could turn the problem on its head and use Hook::WrapSub to track your caller stack yourself, by writing push and pop wrappers that maintain a stack, around the functions you're interested in tracking.

Apart from that, I'm not surprised you find your code as shown to be slow... it has an infinite loop! update: err, no you're right it hasn't. Nonetheless, C-style for loops are so rare in Perl that I probably won't be the only person who gets confused by it (... I was looking for a last somewhere I guess).

You should I think it would be more readable to recast it as something like:

my $level = 0; while (my @frame = caller($level++)) { # do stuff with the current frame }

update: I didn't realise at first that you only cared about the depth, not what's at each level. In which case, the following snippet will be pretty efficient (since it is blockless):

my $level = 0; 1 while caller(++$level);

I wouldn't worry about it being too slow, and least not right away. Make it readable first.

• another intruder with the mooring in the heart of the Perl


In reply to Re: Getting the size of the call stack (efficiently) by grinder
in thread Getting the size of the call stack (efficiently) by DrWhy

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.