Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the name of the current subroutine in Perl?

Tags:

perl

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.

like image 512
kiruthika Avatar asked Apr 01 '10 10:04

kiruthika


People also ask

How do you find a subroutine in Perl?

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.

What is used to identify the subroutine?

Exp: & Symbol is used to identify subroutine in Perl.

What does @_ do 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.


1 Answers

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)'.

like image 151
Eugene Yarmash Avatar answered Oct 09 '22 08:10

Eugene Yarmash