开发者

Get line number from character position

开发者 https://www.devze.com 2023-04-10 21:18 出处:网络
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开发者_如何学运维?If you are reading from a filehandle line

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开发者_如何学运维?


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 $.;


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号