确定 Perl 代码引用的子例程名称
如何确定 Perl 代码引用的子例程名称?我还想区分命名子例程和匿名子例程。
感谢 这个问题 我知道如何打印代码,但我仍然不知道如何获得这个名字。
例如,我想从以下内容获取“inigo_montoya”:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
$Data::Dumper::Deparse = 1;
my $sub_ref = \&inigo_montoya;
print Dumper $sub_ref;
# === subroutines ===
sub inigo_montoya {
print <<end_quote;
I will go up to the six-fingered man and say, "Hello. My name is Inigo
Montoya. You killed my father. Prepare to die."';
end_quote
}
How would one determine the subroutine name of a Perl code reference? I would also like to distinguish between named and anonymous subroutines.
Thanks to this question I know how to print out the code, but I still don't know how to get the name.
For example, I'd like to get 'inigo_montoya' from the following:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
$Data::Dumper::Deparse = 1;
my $sub_ref = \&inigo_montoya;
print Dumper $sub_ref;
# === subroutines ===
sub inigo_montoya {
print <<end_quote;
I will go up to the six-fingered man and say, "Hello. My name is Inigo
Montoya. You killed my father. Prepare to die."';
end_quote
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为什么不问,编译器看到了什么? (它会在匿名订阅者上返回
__ANON__
)。Why not ask, what the compiler sees? (It would return
__ANON__
on anonymous subs).Sub::Identify 正是这样做的,隐藏了所有令人讨厌的
B::svref_2object( )
来自您的东西,这样您就不必考虑它。哪个输出:
Sub::Identify does exactly this, hiding all that nasty
B::svref_2object()
stuff from you so you don't have to think about it.Which outputs:
扩展 Jan Hartung 的想法(并废弃我自己的想法),您可以获得完全限定的名称和一些跟踪信息,无论它是什么或来自哪里:
Expanding on Jan Hartung's idea (and scrapping my own), you could get a fully qualified name and some trace information for no matter what it is or where it came from:
我不确定从外部调用函数的名称,但您可以通过
caller
函数:它具有以下输出:
当然,您可以将函数名称作为子例程返回的项目之一返回。这样,您可以捕获它并可以选择显示它(或在其他逻辑中使用它等)。
I'm not sure about calling the name of the function from the outside, but you can get it from within the subroutine via the
caller
function:This has the following output:
Of course, you can return the function name as one of the items that the subroutine returns. That way, you can capture it and have the option of displaying it (or using it in other logic, etc).