<?xml version="1.0" encoding="windows-1252"?>
<node id="644041" title="Reading partial lines/strings from a pipe" created="2007-10-10 13:46:27" updated="2007-10-10 09:46:27">
<type id="115">
perlquestion</type>
<author id="644031">
slightly72</author>
<data>
<field name="doctext">
Hi all,

&lt;br&gt;&lt;br&gt;I am trying to write some Perl code to communicate with a server. The issue here is that the server replies with strings (i.e. not full lines) -- for example, a query for some port number is answered with "XXXX" and not "XXXX\n" (or any other line/string terminator). I am using open2 to launch the server:

&lt;br&gt;&lt;code&gt;use IO::Handle;&lt;br&gt;
my ($wrt, $rdr) = (IO::Handle-&gt;new(), IO::Handle-&gt;new());
my $procid = open2($wrt, $rdr, $server_command_line);
&lt;/code&gt;

Then at some point I write the command to the stdin of the server (now piped through $wrt). The problem is with reading from the stdout of the server, piped through $rdr.

&lt;br&gt;If I try:

&lt;br&gt;&lt;code&gt;my $reply = &lt;$rdr&gt;;&lt;/code&gt;&lt;br&gt;

the program deadlocks since a full line is expected but never arrives.

&lt;br&gt;&lt;br&gt;I've tried to read character by character from the file (it's not a large performance penalty since the replies are quite short, at most 8-10 chars long) -- however, I don't know when to stop reading these characters, if I'm trying to read over the length of the reply, I get deadlocked again.

&lt;br&gt;&lt;br&gt;The replies are in no particular format or fixed length.

&lt;br&gt;&lt;br&gt;Ideally, I would like to handle the reply with something like:

&lt;br&gt;&lt;code&gt;while (1) {
  if (there_is_something_to_read($rdr)) {
    $reply = get_everything_from_the_pipe($rdr);
    last;
  }
}&lt;/code&gt;

I have looked into File::Tail, but that seems to work only for regular files and not pipes. I've looked also into using threads, as per a reply to a similar problem on perlmonks, but again the issue is that that solution worked with 'records' (i.e. usually lines).

&lt;br&gt;The server is proprietary software, so I can't get into the sources to modify the replies.

&lt;br&gt;&lt;br&gt;Right now, I'm at a loss for a solution, so any help is really appreciated. Oh, and if the solution is not too OS dependent (my script should work on both Linux and Windows) it would be terrific.
&lt;br&gt;&lt;br&gt;Thank you in advance,
&lt;br&gt;Tibi
</field>
</data>
</node>
