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