What is the most convenient way to extract a specified byte range of a file on disk into a variable?
seek
to the start of the range, read
the desired number of bytes (or sysseek
/sysread
-- see nohat's comment).
open $fh, '<', $filename;
seek $fh, $startByte, 0;
$numRead = read $fh, $buffer, $endByte - $startByte; # + 1
&do_something_with($buffer);
Sometimes I like to use File::Map, which lazily loads a file into a scalar. That turns it into string operations instead of filehandle operations:
use File::Map 'map_file';
map_file my $map, $filename;
my $range = substr( $map, $start, $length );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With