my $sock_in = ...; my $fh_out = ...; my $bytes_to_read = ...; while ($bytes_to_read > 0) { my $bytes_read = read($sock_in, my $block = '', $bytes_to_read); if (!$bytes_read) { my $msg = defined($bytes_read) ? 'Socket closed unexpectedly' : $!; die("Unable to read from sender: $msg\n"); } $bytes_to_read -= $bytes_read; print $fh_out $block; }