函数可以告诉它从哪个模块调用吗?

gcb*_*son 4 perl

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).
}
Run Code Online (Sandbox Code Playgroud)

优选地,这将在没有显式传递包含调用模块名称的参数的情况下完成.

mob*_*mob 6

内置caller函数可用于获取有关当前调用堆栈的信息.

 sub fooit {
     my ($pkg, $file, $line) = caller;
     print STDERR "fooit was called from the $pkg package, $file:$line\n";
 }
Run Code Online (Sandbox Code Playgroud)