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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|