Determining the subroutine name of a Perl code reference

后端 未结 4 1255
隐瞒了意图╮
隐瞒了意图╮ 2020-12-29 05:14

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 quest

4条回答
  •  隐瞒了意图╮
    2020-12-29 06:07

    Sub::Identify does exactly this, hiding all that nasty B::svref_2object() stuff from you so you don't have to think about it.

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    use feature 'say';
    
    use Sub::Identify ':all';
    
    my $sub_ref = \&inigo_montoya;
    
    say "Sub Name: ",   sub_name($sub_ref);
    say "Stash Name: ", stash_name($sub_ref);
    say "Full Name: ",  sub_fullname($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
    }
    

    Which outputs:

    $ ./sub_identify.pl 
    Sub Name: inigo_montoya
    Stash Name: main
    Full Name: main::inigo_montoya
    

提交回复
热议问题