Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current line number of a file open using Perl?

Tags:

file

perl

open my $fp, '<', $file or die $!;  while (<$fp>) {     my $line = $_;     if ($line =~ /$regex/) {         # How do I find out which line number this match happened at?     } }  close $fp; 
like image 334
Lazer Avatar asked May 07 '11 11:05

Lazer


People also ask

How do I count the number of lines in a file in Perl?

This will count the total number of lines in the file. open(FH, "<", "foo. txt"); my $count = 0; while (<FH>) { $count = $.; } close FH; print "$count\n"; To count the number of lines in a file that contain the text "Hello World".

How do I get the first line of a file in Perl?

Solution: Read in the first line, do your processing, then continue reading the file. #!/usr/bin/perl -w use strict; use warnings; my $file = "..."; open (CODE, $file) || die "Couldn't open $file: $!"; print scalar <CODE>; # Print the first line # ...

How do I print a specific line in Perl?

print_line-v2. #!/usr/bin/perl -w # print_line-v2 - Tie::File style use Tie::File; use Fcntl; @ARGV = = 2 or die "usage: print_line FILENAME LINE_NUMBER\n"; ($filename, $line_number) = @ARGV; tie @lines, Tie::File, $filename, mode => O_RDWR or die "Can't open $filename for reading: $!\


1 Answers

Use $. (see perldoc perlvar).

like image 64
ninjalj Avatar answered Sep 26 '22 12:09

ninjalj