1

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?

Borodin
  • 126,100
  • 9
  • 70
  • 144
robbie
  • 1,219
  • 1
  • 11
  • 25
  • Out of curiosity: What is the purpose of the null character in the beginning of the `Peer` name? – Håkon Hægland May 02 '17 at 13:51
  • 1
    @HåkonHægland On Linux, the null character creates an abstract Unix socket. This is a socket that exists outside of the filesystem. – robbie May 02 '17 at 14:36

1 Answers1

2

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>
JRFerguson
  • 7,426
  • 2
  • 32
  • 36