Take the 2-minute tour ×
open my $fp, '<', $file or die $!;

while (<$fp>) {
    my $line = $_;
    if ($line =~ /$regex/) {
        # how to find out which line number this match happened at?

close $fp;
share|improve this question
If you want to read a line into $line, then read a line into $line rather than reading a line into some other variable and then copying it to $line: while (my $line = <$fp>) { –  tadmc May 7 '11 at 13:49
@tadmc: or rather while (defined( my $line = <$fp> )) { ... }, since the last line could be a zero and not end in a newline. –  phaylon May 8 '11 at 17:08

2 Answers 2

up vote 20 down vote accepted

Use $. (see perldoc perlvar).

share|improve this answer
Very technically, $. isn’t necessarily the line number; it is the number of times that the readline operator has been called on the last handle it was called on since that handle’s last close (not open). It would not reflect lines if $/ is not set to "\n" (such as "" or "\n%%\n", or if the handle has had open called on it without a call to close (as occurs with ARGV, and thus with <>). And whether it is meaningful for text files with mangled last lines that don’t have a proper line termination sequence on them I leave for your own contemplation. –  tchrist May 7 '11 at 16:46
@tchrist: Your explanation of edge cases should have been posted as third answer here. –  Dallaylaen May 8 '11 at 17:41

You can also do it through OO interface:

use IO::Handle;
# later on ...
my $n = $fp->input_line_number();

This is in perldoc perlvar, too.

share|improve this answer
That is subject to the same caveats as I just outlined for $., of course. –  tchrist May 7 '11 at 16:48

Your Answer


