tags:

views:

75

answers:

2

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
Why do you need to override the prototype checking on `do_something_with()`?
daotoad
`$fh` hasn't been declared, if you `use strict; use warnings;`
Ether
Crikey - the OP asked for the most convenient way, not the most pedantic way. ;-)
mobrule
I think you mean `sysread $fh, $buffer, $endByte - $startByte +1;`
nohat
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
Finally, this doesn't work because you can't mix `seek` calls with `sysread` calls. You need to use `sysseek` instead.
nohat
thanks @nohat -- fixed and fixed
mobrule
+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