Reputation: 3665
How can I locate the line where character n in file is located?
For example, how can I know where character 5347 is located in a given file?
Upvotes: 3
Views: 734
Reputation: 1189
If you are reading from a filehandle line by line with line input operator, special variable $.
gives current line.
Here is some sample code: it reads a file line, counting characters with $pos
.
#!/usr/bin/env perl
use v5.12;
use strict;
open my $fh, '<', 'file.txt';
my $reference = 5347;
my $pos = 0;
do {
$pos += length <$fh>;
} while ( $pos < $reference );
say $.;
Upvotes: 5
Reputation: 7475
This lightly tested code seemed to me to do the job:
my $desired = 5347;
my $char_count = 0;
while ( <$fh> ) {
$count += length;
if ( $count >= $desired ) {
print $. . $/;
last;
}
}
Of course it assumes that $fh
is an already opened filehandle that hasn't been read from yet.
Also note that it counts characters, not bytes, which is what you said, but might not have been what you meant.
Upvotes: 3