Reputation: 49822
Is it possible to get the current source line number in Perl?
The equivalent in C++ is __LINE__
.
Upvotes: 39
Views: 39633
Reputation: 95614
The __LINE__
literal is documented in the Special Literals section of the perldata man page.
print "File: ", __FILE__, " Line: ", __LINE__, "\n";
or
warn("foo");
Upvotes: 64
Reputation: 809
Note there's a gotcha with
perl -e 'warn("foo")'
Output:
foo at -e line 1.
If it ends with a newline it won't print the line number:
perl -e 'warn("foo\n")'
Output:
foo
This is documented in perldoc -f die
, but it is perhaps easy to miss in the perldoc -f warn
section's reference to die
.
Upvotes: 8
Reputation: 19
"use Carp" and play with the various routines and you also get a stack; I am 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 I have seen little value outside a debug environment.
Upvotes: 2
Reputation: 1731
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"; }
Upvotes: 2