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

Is there an easy way to get the depth of the current call stack? I just recently discovered the "caller" function, and it's been a great help in debugging. But I'd like a way to know how many calls deep I am at any given point, so I can indent my trace log appropriately.

---
A fair fight is a sign of poor planning.

Replies are listed 'Best First'.
Re: Getting size of call stack
by diotalevi (Canon) on Nov 07, 2003 at 16:19 UTC

    Increment the depth until you get nothing back.

    Update 1: Oops. I accidentally declared $depth twice.
    Update 2: I accidentally put a semi-colon after `my depth = 0` which screws up the parameters for the for(;;). Replacing it with a comma keeps the correct meaning.

    my @stack; for ( my $depth = 0, my $frame = [ caller $depth ]; scalar( @$frame ); $depth++ ) { push @stack, $frame; }
      I like that you have both the stack to inspect (eg. dump it to stderr) and the stack depth (scalar(@stack))

      For my liking though, this is more intuitive:

      my @stack; my $depth = 0; while (my @frame = caller $depth++) { push @stack, \@frame[0,1,2]; }
        The entire purpose of the for(;;) loop is to handle preinitializations and temporary variables like your my $depth = 0 and to separate your test scalar( @frame ) from your NEXT() in $depth++.
Re: Getting size of call stack
by broquaint (Abbot) on Nov 07, 2003 at 16:40 UTC
    my $depth = 0; $depth++ while caller($depth);
    Will give you the depth of the stack for the current frame in the $depth variable.
    HTH

    _________
    broquaint

      Yes, this works fine. I tweaked it a bit, setting $depth to -1 and putting the code in a GetCallStackDepth sub. Cool!

      ---
      A fair fight is a sign of poor planning.

        I tweaked it a bit, setting $depth to -1

        Wouldn't your subroutine always return -1? Shouldn't your GetCallStackDepth look more like:

        sub GetCallStackDepth { my $depth = 1; # 0 is this sub, why bother checking it? $depth++ while caller($depth); return $depth - 1; }