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. |