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

Re: Re: caller counter

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

in reply to Re: caller counter
in thread caller counter

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?

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2021-09-18 17:26 GMT
Find Nodes?
    Voting Booth?

    No recent polls found