Is it possible to get the current source line number in Perl?
The equivalent in C++ is __LINE__
.
Asked
Active
Viewed 3.8k times
39

brian d foy
- 129,424
- 31
- 207
- 592

David Sykes
- 48,469
- 17
- 71
- 80
-
I'm wondering though: why would you need this? – Leon Timmermans Dec 10 '08 at 11:36
-
5I've used it to quickly track the progress through a very long process, and to check the order things are done in, like breakpoints but without using the debugger – David Sykes Dec 15 '08 at 09:11
-
@LeonTimmermans: I am responding to your very old comment about why a Perl programmer might want _ _FILE_ _ and _ _ LINE _ _. Basically, the same reasons why a C/C++ programmer might want them. E.g. today I refactored a test so that Test::Differences::eq_or_diff was called in a subroutine. The line number reported was in the subroutine not where the subroutine was called from. Adding __ LINE __ to the test name helps me find the failing test. Now if I could just write a macro CODE_LOCATION in Perl5. – Krazy Glew Nov 22 '15 at 21:42
4 Answers
64
The __LINE__
literal is documented in the Special Literals section of the perldata man page.
print "File: ", __FILE__, " Line: ", __LINE__, "\n";
or
warn("foo");

mivk
- 13,452
- 5
- 76
- 69

Eugene Yokota
- 94,654
- 45
- 215
- 319
-
Maybe I do bad google searches, though in 99.999% they are very precise for me. For this question I search with a sentence 'how to print current line in perl' basically, and I got only replies regards outputting the line number from the file read with `$.`, which is trivial as incrementing variable in a loop reading lines. So I wonder if many other people would not have the same issue. Interestingly enough, it seems as if Google put this question among search results once I searched for it differently, or I just overlooked it at my initial attempts. – FantomX1 Oct 19 '20 at 13:40
8
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
.

brian d foy
- 129,424
- 31
- 207
- 592

bigiain
- 809
- 5
- 8
2
"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.

user4155330
- 19
- 1