Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

file

perl

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

like image 585
nohat Avatar asked Feb 27 '23 04:02

nohat


2 Answers

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);
like image 77
mob Avatar answered Mar 16 '23 00:03

mob


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 );
like image 27
brian d foy Avatar answered Mar 15 '23 23:03

brian d foy