Sunday, September 18, 2011

Using the caller() Function in Subroutines

The caller() function can be used in a subroutine to find out information about where the
subroutine was called from and how it was called. Caller takes one argument that
indicates how far back in the call stack to get its information from. For information about
the current subroutine, use caller(0).
sub HowWasICalled {
my @info = caller(0);
print Dumper \@info;
}
HowWasICalled;
>$VAR1 = [
> 'main',
> './test.pl',
> 13,
> 'main::HowWasICalled',
> 1,
> undef,
> undef,
> undef,
> 2,
> 'UUUUUUUUUUUU'
> ];

The caller() function returns a list of information in the following order
0 $package package namespace at time of call
1 $filename filename where called occurred
2 $line line number in file where call occurred
3 $subroutine name of subroutine called
4 $hasargs true if explicit arguments passed in
5 $wantarray list=1, scalar=0, void=undef
6 $evaltext evaluated text if an eval block
7 $is_require true if created by "require" or "use"
8 $hints internal use only, disregard
9 $bitmask internal use only, disregard

No comments: