In Perl we can get the name of the current package and current line number Using the predefined variables like __PACKAGE__
and __LINE__
.
Like this I want to get the name of the current subroutine:
use strict; use warnings; print __PACKAGE__; sub test() { print __LINE__; } &test();
In the above code I want to get the name of the subroutine inside the function test
.
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.
Exp: & Symbol is used to identify subroutine in Perl.
The @_ variable is an array that contains all the parameters passed into a subroutine. The parentheses around the $string variable are absolutely necessary. They designate that you are assigning variables from an array.
Use the caller()
function:
my $sub_name = (caller(0))[3];
This will give you the name of the current subroutine, including its package (e.g. 'main::test'
). Closures return names like 'main::__ANON__'
and in eval it will be '(eval)'
.
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