package Bar;
use Foo;
sub bar { fooit "hello from bar"; }
package Foo;
sub fooit {
# Somehow I want this function to know it was called
# from the "Bar" module (in this case).
}
优选地,这将在不显式传递包含调用模块名称的参数的情况下完成。
package Bar;
use Foo;
sub bar { fooit "hello from bar"; }
package Foo;
sub fooit {
# Somehow I want this function to know it was called
# from the "Bar" module (in this case).
}
优选地,这将在不显式传递包含调用模块名称的参数的情况下完成。
内置caller
函数可用于获取有关当前调用堆栈的信息。
sub fooit {
my ($pkg, $file, $line) = caller;
print STDERR "fooit was called from the $pkg package, $file:$line\n";
}
caller
在标量上下文中没有参数将返回调用者的命名空间。
my $caller = caller();
或者
print caller()."\n"; # '.' forces scalar context
或者
print "".caller(), "\n"; # '.' forces scalar context
除非您尝试复制Carp的潜艇之一的行为,否则您很少需要它。
使用 builtincaller
应该是最简单直接的方法,但Devel::Backtrace也是一个值得一看的 CPAN 模块,它可以通过优雅的界面提供更多详细信息。
package Foo;
use Devel::Backtrace;
sub fooit {
my $backtrace = Devel::Backtrace->new;
print $backtrace->point(1)->package, "\n\n";
print $backtrace;
}
package Bar;
sub bar {
Foo::fooit('hello from bar');
}
package main;
Bar::bar();
输出:
Bar
Devel::Backtrace::new called from Foo (test.pl:5)
Foo::fooit called from Bar (test.pl:14)
Bar::bar called from main (test.pl:19)