4
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).
}

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

4

3 回答 3

6

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

 sub fooit {
     my ($pkg, $file, $line) = caller;
     print STDERR "fooit was called from the $pkg package, $file:$line\n";
 }
于 2013-03-08T17:37:24.463 回答
2

caller在标量上下文中没有参数将返回调用者的命名空间。

my $caller = caller();

或者

print caller()."\n";       # '.' forces scalar context

或者

print "".caller(), "\n";   # '.' forces scalar context

除非您尝试复制Carp的潜艇之一的行为,否则您很少需要它。

于 2013-03-08T17:38:37.430 回答
1

使用 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)
于 2013-03-09T10:40:18.277 回答