如何确定Perl代码引用的子例程名称?我还想区分命名子例程和匿名子例程。

感谢this question,我知道如何打印代码,但是我仍然不知道如何获得名称。

例如,我想从以下代码中获取“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
}

最佳答案

为什么不问,编译器看到了什么? (它将在匿名订阅中返回__ANON__)。

#!/usr/bin/perl

use strict;
use warnings;

my $sub_ref = \&inigo_montoya;


use B qw(svref_2object);
my $cv = svref_2object ( $sub_ref );
my $gv = $cv->GV;
print "name: " . $gv->NAME . "\n";


sub inigo_montoya {
    print "...\n";
}

09-10 01:35
查看更多