How can I access a specific range of bytes in a file using Perl?

What is the most convenient way to extract the specified byte range of a file on disk into a variable?

+4
source share
2 answers

seek before the start of the read range the desired number of bytes (or sysseek / sysread - see nohat comment).

 open $fh, '<', $filename; seek $fh, $startByte, 0; $numRead = read $fh, $buffer, $endByte - $startByte; # + 1 &do_something_with($buffer); 
+5
source

Sometimes I like to use File :: Map , which lazily loads the file into a scalar. This turns it into string operations instead of file descriptor operations:

  use File::Map 'map_file'; map_file my $map, $filename; my $range = substr( $map, $start, $length ); 
+3
source

Source: https://habr.com/ru/post/1307178/


All Articles