How can I print source line number in Perl?
-
21-08-2019 - |
Question
Is it possible to get the current source line number in Perl?
The equivalent in C++ is __LINE__
.
Solution
print "File: ", __FILE__, " Line: ", __LINE__, "\n";
or
warn("foo");
OTHER TIPS
The __LINE__ literal is documented in the Special Literals section of the perldata man page.
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...
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"; }
"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.