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.


In reply to Re: Re: caller counter by !1
in thread caller counter by wolis

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.