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

In reply to Re: Reading from a pipe line by line by ikegami
in thread Reading from a pipe line by line by Marcello

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.