Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: caller counter

by !1 (Hermit)
on Dec 04, 2003 at 01:19 UTC ( #312070=note: print w/replies, xml ) Need Help??


in reply to caller counter

I'm short on time but I know this question has been asked before. The sub looked something like:

sub stack_depth() { my $depth = 1; $depth++ while defined caller($depth); --$depth; }

I think that's right.

Replies are listed 'Best First'.
Re: caller counter
by Abigail-II (Bishop) on Dec 04, 2003 at 10:17 UTC
    If you start with my $depth = 0;, there's no need for the final -- $depth.

    Abigail

      Sorry to disagree, but that would only be if the contents of stack_depth were used as a snippet in place of the subroutine.

      I know you know this, but for those who don't:

      sub stack_depth() { my $depth = 1; $depth++ while defined caller($depth); --$depth; }

      This subroutine is meant to be used as in the following snippet:

      #!/usr/bin/perl -wl use strict; sub stack_depth() { my $depth = 1; $depth++ while defined caller($depth); --$depth; } sub test1 { print stack_depth;test2() } # should be 1 sub test2 { print stack_depth;test3() } # should be 2 sub test3 { print stack_depth } # should be 3 print stack_depth; # what's our stack depth here? should be 0 test1(); __END__ outputs: 0 1 2 3

      The reason that $depth is set to 1 instead of to 0 in the subroutine is because we're interested in the depth of the stack from wherever the subroutine was called. Since stack_depth itself is a subroutine, we already know that it will have been placed on the stack. Thus we know caller(0) will be defined. When the loop completes, $depth will contain the depth of our subroutine regardless of whether we set $depth = 0 or $depth = 1. Thus the reason for --$depth as the implicit return.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://312070]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (5)
As of 2021-09-17 19:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?