For the sake of diversity, how about splitting and creating an array of offsets? Something like this:
my @strings = split "\n", $string; my @lookup; $lookup[0] = 0; foreach my $i ( 1..$#strings ) { # byte offset of 1st char on this line $lookup[$i] = length($strings[$i-1]) + $lookup[$i-1]; }
Here's a complete program, including the binary search routine. (Not completely tested, but seems to work, and gives the general idea.)
#!/your/perl/here use strict; use warnings; my $string = <<EOS; one two three four five six EOS my @strings = split "\n", $string; my @lookup; $lookup[0] = 0; foreach my $i ( 1..$#strings ) { # byte offset of 1st char on this line $lookup[$i] = length($strings[$i-1]) + $lookup[$i-1]; } my ($line, $offset) = find_line_offset( $ARGV[0] ); print "line: $line, offset: $offset\n"; exit; sub find_line_offset { my $offset = shift; my $lo = 0; my $hi = $#lookup; my $line; while ($lo+1 < $hi) { $line = int(($hi+$lo)/2); if ( $lookup[$line] > $offset ) { $hi = $line; } elsif ( $lookup[$line] < $offset ) { $lo = $line; } else { # small chance it's equal last; } } # could have overshot 1 if ( $lookup[$line] > $offset ) { $line--; } if ( $lookup[$line+1] > $offset ) { # this is the one my $line_offset = ($offset - $lookup[$line]); return ($line, $line_offset); } else { return; } }

I'm sure there are numerous improvements that can be made (including error checking), so hack away!

-QM
--
Quantum Mechanics: The dreams stuff is made of


In reply to Re: Find line number and offset inside line given a byte offset in string by QM
in thread Find line number and offset inside line given a byte offset in string by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.