in reply to Mixing sysread() with <FILEHANDLE>?

I would make sure you are not mixing buffered and unbuffered I/O on the same file handle. That is, the client should not use both print and syswrite, and the server should not read from STDIN using readline (or equivalently <STDIN>) and sysread - it will just cause you a lot of problems.

To solve your binary data problem, how about implement a simple encoding scheme?

sub write_binary { my $fh = shift; my $data = shift; print $fh unpack("H*", $data), "\n"; } sub read_binary { my $fh = shift; my $line = <$fh>; chomp; return pack("H*", $line); }
The point is that interaction with a network server is done via sending and receiving messages, and so it's natural to have subroutines or methods to perform those functions:
my $server = ...; $server->send_message("Hello"); ... $msg = $server->receive_message(); ...
Encapsulating the interaction this way allows you to easily later change how the message sending is performed (use of syswrite or print, choice of encoding, etc.) Moreover, you'll need this encoding layer if you ever want to transmit anything more complex than a simple octet string. So if you want to send two data values, or an array of values or even Unicode code-points, you'll need an encoding layer.

Replies are listed 'Best First'.
Re^2: Mixing sysread() with <FILEHANDLE>?
by wanna_code_perl (Friar) on May 26, 2008 at 22:42 UTC

    Thank you, this is very helpful.

    I would indeed prefer not to have to use syswrite. Encoding with pack makes sense, but is there a more space-efficient way to portably transfer the data? Even with uuencoding pack("u*"), there is a 1/3 increase in required bandwidth. (True, SSH compression would mostly negate that if it is enabled, which I can not guarantee).

    I need to transmit blobs of raw binary data, up to several gigabytes in a single session hence I do need to optimize for size. For my application, it's the raw bits that are important and need to be preserved. I will never be transmitting any higher-order structure.

    Thank you for the advice about encapsulation as well. I have already done that. Now I just need a transmission method that works. :)