use strict; use warnings; use autodie; my $filename = '...some filename...'; my $rangeStart = 10_000; my $rangeEnd = 20_000; open my $fh, "<", $filename; binmode $fh; seek($fh, $rangeStart, 0); my $total_bytes_to_read = $rangeEnd - $rangeStart + 1; my $buffer_size = 1_024; my $buffer; my $num_bytes_to_read; my $num_bytes_actually_read; # read() : Returns the number of characters actually read, 0 at end of file, or undef if there was an error (in the latter case $! is also set) while ( ( $num_bytes_to_read = ($buffer_size <= $total_bytes_to_read) ? $buffer_size : $total_bytes_to_read ), # handle partial buffer ( $num_bytes_actually_read = read($fh, $buffer, $num_bytes_to_read) ), ( (defined $num_bytes_actually_read) && ($num_bytes_actually_read > 0) ) ) { $total_bytes_to_read -= $num_bytes_actually_read; # process $num_bytes_actually_read in $buffer } if ( ! defined $num_bytes_actually_read ) { die $! } # there was an error. In this example, autodie will detect this, but # without autodie you'd need to check it yourself. ( $num_bytes_actually_read == 0 ) || die "Should never happen"; # if $total_bytes_to_read > 0, then reached EOF before reading all specified data # ie $rangeEnd > size of $filename