Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the filename and line number in Perl?

Tags:

perl

I would like to get the current filename and line number within a Perl script. How do I do this?

For example, in a file call test.pl:

my $foo = 'bar';
print 'Hello, World!';
print functionForFilename() . ':' . functionForLineNo();

It would output:

Hello, World!
test.pl:3
like image 380
Elijah Avatar asked Nov 01 '10 17:11

Elijah


3 Answers

These are available with the __LINE__ and __FILE__ tokens, as documented in perldoc perldata under "Special Literals":

The special literals __FILE__, __LINE__, and __PACKAGE__ represent the current filename, line number, and package name at that point in your program. They may be used only as separate tokens; they will not be interpolated into strings. If there is no current package (due to an empty package; directive), __PACKAGE__ is the undefined value.

like image 161
Ether Avatar answered Oct 13 '22 21:10

Ether


The caller function will do what you are looking for:

sub print_info {
   my ($package, $filename, $line) = caller;
   ...
}

print_info(); # prints info about this line

This will get the information from where the sub is called, which is probably what you are looking for. The __FILE__ and __LINE__ directives only apply to where they are written, so you can not encapsulate their effect in a subroutine. (unless you wanted a sub that only prints info about where it is defined)

like image 29
Eric Strom Avatar answered Oct 13 '22 22:10

Eric Strom


You can use:

print __FILE__. " " . __LINE__;
like image 32
codaddict Avatar answered Oct 13 '22 21:10

codaddict