in reply to Find line number and offset inside line given a byte offset in string

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