如何在 Perl 中获取当前子程序的名称? [英] How can I get the name of the current subroutine in Perl?
问题描述
在 Perl 中,我们可以使用诸如 __PACKAGE__
和 __LINE__
之类的预定义变量来获取当前包的名称和当前行号.
In Perl we can get the name of the current package and current line number Using the predefined variables like __PACKAGE__
and __LINE__
.
像这样我想得到当前子程序的名字:
Like this I want to get the name of the current subroutine:
use strict;
use warnings;
print __PACKAGE__;
sub test()
{
print __LINE__;
}
&test();
在上面的代码中,我想获取test
函数内子程序的名称.
In the above code I want to get the name of the subroutine inside the function test
.
推荐答案
caller是在 @eugene 指出的正确方法 如果你想在子程序中这样做.
caller is the right way to do at @eugene pointed out if you want to do this inside the subroutine.
如果您希望程序的另一部分能够识别代码引用的包和名称信息,请使用 Sub::Identify.
If you want another piece of your program to be able to identify the package and name information for a coderef, use Sub::Identify.
顺便说一下
sub test()
{
print __LINE__;
}
&test();
有几点要提:首先,不要使用原型 除非您试图模仿内置函数.其次,调用子程序&> 除非您特别需要它提供的效果.
there are a few important points to mention: First, don't use prototypes unless you are trying to mimic builtins. Second, don't use &
when invoking a subroutine unless you specifically need the effects it provides.
因此,该片段最好写成:
Therefore, that snippet is better written as:
sub test
{
print __LINE__;
}
test();
这篇关于如何在 Perl 中获取当前子程序的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!