How can I print source line number in Perl?

36,150

Solution 1

The __LINE__ literal is documented in the Special Literals section of the perldata man page.

print "File: ", __FILE__, " Line: ", __LINE__, "\n";

or

warn("foo");

Solution 2

Note there's a gotcha with

perl -e'warn("foo")'

foo at -e line 1.

if it ends with a newline it won't print the line number

perl -e'warn("foo\n")'

foo

This is documented in "perldoc -f die", but is perhaps easy to miss in the "perldoc -f warn" section's reference to die...

Solution 3

"use Carp" and play with the various routines and you also get a stack - not sure if this way is better or worse than the "caller" method suggested by cnd. I have used the LINE and FILE variables (and probably other similar variables) in C and Perl to show where I got in the code and other information when debugging but have seen little value outside a debug environment.

Solution 4

This prints out the line where you are, and also the "stack" (list of lines from the calling programs (scripts/modules/etc) that lead to the place you are now)

while(my @where=caller($frame++)) { print "$frame:" . join(",",@where) . "\n"; }
Share:
36,150
David Sykes
Author by

David Sykes

Updated on May 09, 2020

Comments

  • David Sykes
    David Sykes almost 4 years

    Is it possible to get the current source line number in Perl? The equivalent in C++ is __LINE__.