caller函数

在写perl中,调试代码要查看是谁调用谁,caller就比较方便实现这个功能

($package, $filename, $line) = caller;
返回包名、文件名、调用的行号

caller返回一数组,可以数组下标来取具体值

$cat caller.pl
#!/usr/bin/perl
#use strict;
#use warnings;
sub b{
    my $sub=(caller(0))[3];
    print "subroutine $sub\n";
    print caller()."\n";
    print caller(0);
}
&b;
 
$perl caller.pl
subroutine main::b
main
maincaller.pl10main::b0256

解释:caller(0)[3]取得是子程序名,caller中参数0代表当前堆栈

$cat caller.pl 
#!/usr/bin/perl
#use strict;
#use warnings;
sub c{
    my $sub=(caller(0))[3];
    print "subroutine $sub\n";
    print caller(1);
    print "\n";
    print caller(2);
    print "\n";
}
sub b{
    my $sub=(caller(0))[3];
    print "subroutine $sub\n";
    print caller(1);
    print "\n";
    &c
}
sub a{
    my $sub=(caller(0))[3];
    print "subroutine $sub\n";
    &b;
}
&a;
 
$perl caller.pl 
subroutine main::a
subroutine main::b
maincaller.pl24main::a0256
subroutine main::c
maincaller.pl22main::b0256
maincaller.pl24main::a0256

解释:caller(1)是返回调用者、caller(2)返回调用的调用者

参考:
http://perldoc.perl.org/functions/caller.html
http://blog.csdn.net/ace_fei/article/details/6851882


Post a Comment