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;
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".
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 # ...
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: $!\
Use $.
(see perldoc perlvar
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With