http://www.perlmonks.org?node_id=11107298

phoenix007 has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks. I want to find length of line if I have any position in that line

What im doing currently is creating array where "\n" is present. Then finding pair of "\n" surrounding my position and then taking differnce between position of those two new lines as length of line

I want to optimise it to find position of newline before and after postion and find length instead of building array every time

my $string ="test\nI want length of this line\n test"; my $position = 12; # Note this postion can be any position in any line +. currently considering it inside 2nd line my @newlines; # for storing \n positions push @newlines, 0; while ($string =~/\n/g) { push @newlines, pos($string); } my itr = scalar @newlines - 1; while ($newlines[$itr] > $position) { $itr--; } my $length_of_line = $newlines[$itr + 1] - $newlines[$itr]; #Better efficient solution to find length of line if we have only any +position inside it. Thanks in advance!!!