I have a server running socat
with this command:
socat ABSTRACT-LISTEN:test123 PIPE
I can open a socket to this server, send one line, read one line, and print it with this code:
#!/usr/bin/perl
use strict;
use warnings;
use IO::Socket::UNIX;
my $sock = IO::Socket::UNIX->new(
Type => SOCK_STREAM(),
Peer => "\0test123"
) or die "Error creating socket: $!\n";
print $sock "Hello, world!\n";
my $line = <$sock>;
close $sock;
print $line;
When I replace the last 5 lines with the following, however, the program hangs:
print <$sock>;
Isn't the <FILEHANDLE>
operator supposed to read one line from the handle? Why can I not read one line and print it?
print <$sock>
is imposing list context to readline and thus reads and returns all lines until the end-of-file.
As noted in perlop :
If a is used in a context that is looking for a list, a list comprising all input lines is returned, one line per list element.
As noted by Hakon-Haegland in his comment below, a concise way to read only one line is to impose scalar context:
print scalar <$sock>