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).
}
最好不要显式传递包含调用模块名称的参数。
答案 0 :(得分:6)
内置caller
函数可用于获取有关当前调用堆栈的信息。
sub fooit {
my ($pkg, $file, $line) = caller;
print STDERR "fooit was called from the $pkg package, $file:$line\n";
}
答案 1 :(得分:2)
caller
在标量上下文中没有参数将返回调用者的命名空间。
my $caller = caller();
或
print caller()."\n"; # '.' forces scalar context
或
print "".caller(), "\n"; # '.' forces scalar context
除非你试图复制Carp个潜艇之一的行为,否则很少需要它。
答案 2 :(得分:1)
使用内置caller
应该是最简单,最直接的方法,但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)