nohat
nohat

Reputation: 7281

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

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

Upvotes: 4

Views: 736

Answers (2)

brian d foy
brian d foy

Reputation: 132920

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 );

Upvotes: 3

mob
mob

Reputation: 118695

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);

Upvotes: 5

Related Questions