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 }
A Perl subroutine or function is a group of statements that together performs a task. You can divide up your code into separate subroutines. How you divide up your code among different subroutines is up to you, but logically the division usually is so each function performs a specific task.
The word subroutines is used most in Perl programming because it is created using keyword sub. Whenever there is a call to the function, Perl stop executing all its program and jumps to the function to execute it and then returns back to the section of code that it was running earlier.
Exp: & Symbol is used to identify subroutine in Perl.
Perl subroutine syntax First, you use sub keyword followed by the name of the subroutine. Because subroutine has its own namespace, you can have a subroutine named &foo and a scalar named $foo . We will explain the ampersand (&) in the subroutine name later.
Why not ask, what the compiler sees? (It would return __ANON__
on anonymous subs).
#!/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"; }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With