vlee vlee - 14 days ago 4x
Perl Question

Determining the subroutine name of a Perl code reference

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."';


Why not ask, what the compiler sees? (It would return __ANON__ on anonymous subs).


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";