What is the most convenient way to extract a specified byte range of a file on disk into a variable?
+5
A:
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);
mobrule
2010-04-16 19:23:41
Why do you need to override the prototype checking on `do_something_with()`?
daotoad
2010-04-16 19:57:59
`$fh` hasn't been declared, if you `use strict; use warnings;`
Ether
2010-04-16 20:06:19
Crikey - the OP asked for the most convenient way, not the most pedantic way. ;-)
mobrule
2010-04-16 20:30:29
I think you mean `sysread $fh, $buffer, $endByte - $startByte +1;`
nohat
2010-04-16 20:35:33
Also, the order of the parameters to seek is backwards. It's seek FILEHANDLE,POSITION,WHENCE so it should be `seek $fh, $startByte, 0`
nohat
2010-04-16 20:45:23
Finally, this doesn't work because you can't mix `seek` calls with `sysread` calls. You need to use `sysseek` instead.
nohat
2010-04-16 20:48:36
thanks @nohat -- fixed and fixed
mobrule
2010-04-16 21:00:43
+3
A:
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 );
brian d foy
2010-04-17 13:14:45