So do a second read. Nothing guarantees you'll get the number of bytes you've requested.
use Carp qw( croak );
sub sysread_full
my $fh = $_[0]
our $buf; local *buf = \$_[1]; # alias
my $to_read = $_[2]
my $offset = $_[3] || 0;
$offset += length($buf) if $offset < 0;
croak("Offset outside string") if $offset < 0;
my $tot_read = 0;
while ($to_read > 0) {
my $bytes_read =
sysread($fh, $buf, $to_read, $offset+$tot_read);
return undef if !defined($bytes_read);
return $tot_read if !$bytes_read;
$to_read -= $bytes_read;
$tot_read += $bytes_read;
}
return $tot_read;
}
...
sysread_full $sock, $read_length, 20;
sysread_full $sock, $buffer, $read_length;
...
The behaviour I've observed follows: If there are bytes available to be read, they will be returned immediately, even if there are fewer than requested. (Users of select rely on this.) If there no bytes available to read, it will block.
Update: Added code.
Update: sysread_full differed from sysread in its handling of the offset. Fixed.