title: Perl read seek tell, and text files. Too many bytes being read. Layers and newline handling
body: <p>I've a Perl script which analyses a text file (can be UNIX or windows line endings) storing file offsets when it find something of interest.</p>
  
  <pre><code>open(my $fh, $filename);
  my $groups;
  my %hash;
  while(&lt;$fh&gt;) {
     if($_ =~ /interesting/ ) {
        $hash{$groups++}{offset} = tell($fh);
     }
  }
  close $fh;
  </code></pre>
  
  <p>Then later on in the script I want to produce 'n' copies of the text file but with additional content at each 'interesting' area.  To achieve this I loop through the hash of offsets:</p>
  
  <pre><code>foreach my $group (keys %hash) {
     my $href = $hash{$group};
     my $offset = $href-&gt;{offset};
  
     my $top;
     open( $fh, $file);
     read( $fh, $top, $offset);
     my $bottom = do{local $/; &lt;$fh&gt;};
     close $fh;
  
     $href-&gt;{modified} = $top . "Hello World\n" . $bottom;
  }
  </code></pre>
  
  <p>The problem is the read command is reading too many bytes.  I suspect this is a line ending issue as the number of bytes (chars?) out is the same as the line number.  Using Notepad++ the <code>tell()</code> command is returning the real offset to point of interest, but using that offset value in <code>read()</code> returns characters past the point of interest.</p>
  
  <p>I've tried adding <code>binmode($fh)</code> straight after the <code>open()</code> command prior to the <code>read()</code>.  This does find the correct position in the text file, but then I get (CR + CRLF) output and the text file is full of double carriage returns.</p>
  
  <p>I've played with layers :crlf, :bytes, but no improvement.</p>
  
  <p>Bit stuck!</p>