Elijah
Elijah

Reputation: 13604

How do I get the filename and line number in 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

Upvotes: 6

Views: 8503

Answers (3)

codaddict
codaddict

Reputation: 455072

You can use:

print __FILE__ . " " . __LINE__;

Upvotes: 7

Eric Strom
Eric Strom

Reputation: 40142

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)

Upvotes: 11

Ether
Ether

Reputation: 53966

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.

Upvotes: 14

Related Questions