perl

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

Solution

  • 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.