<FH> reads until the end of the line. You want to read until the end of available data. You need to use sysread.
Simplisticly, sysread($handle, my $message, 1024); will work.
Realisticly, you need something adapted from that which I posted earlier. Give me a couple of minutes, and I will post the necessary code.
Update: I've just found out that -s will return the number of bytes available (on FreeBSD). So all you need is the following:
sysread($handle, my $message, -s $handle);
You will need to split the lines apart, but that shouldn't be a problem.
Update: If you wanted to be super safe — i.e. if you don't want to reply on your OS's implementation details — you could use the following. As a bonus, it still supports multiple child handles.
my %buf;
while (my @handles = $ios->can_read(0)) {
foreach my $handle (@handles) {
$buf{$handle} ||= { buf => '', offset => 0 };
# Aliases to improve readability through conciseness.
our $buf; local *buf = \($buf{$handle}{buf });
our $offset; local *offset = \($buf{$handle}{offset});
#my $len = sysread($handle, $buf, -s $handle, $offset);#Portable?
my $len = sysread($handle, $buf, 1024, $offset);
die("Unable to read from pipe: $!\n")
if not defined $len;
if (not $len) {
$ios->remove($handle);
next;
}
$offset += $len;
for (;;) {
my $pos = index($buf, "\x0A");
last if not ++$pos;
my $message = substr($buf, 0, $pos);
$buf = substr($buf, $pos);
$offset -= $pos;
$message =~ s/\x0A$/\n/; # For Macs.
print "Read message: ".$message;
}
}
}
foreach (keys %buf) {
die("Unable to read from pipe: Premature end of file\n")
if $buf{$_}{offset};
}
|