Question

So I have this problem while looping through a socket with a while loop.

When I use this, it totally works fine but I have newlines on every $message, which I don't want.

my $socket = new IO::Socket::INET (
    LocalHost => "127.0.0.1", 
    LocalPort => "12345", 
    Proto => 'tcp', 
    Listen => 1, 
    Reuse => 1
);
my $client = $socket->accept();
while(<$client>) {
    my $message = $_;
    print $message;
}

But when I add the chomp the loop only finished when I disconnect the client (which I understand why). My guess is that chomp removes the newline from the $_ variable and thus the loop will not work anymore.

my $socket = new IO::Socket::INET (
    LocalHost => "127.0.0.1", 
    LocalPort => "12345", 
    Proto => 'tcp', 
    Listen => 1, 
    Reuse => 1
);
my $client = $socket->accept();
while(<$client>) {
    my $message = $_;
    chomp($message);
    print $message;
}

So my question is: How can I loop through the socket (newline terminated) without having the newlines in the messages?

Thanks a bunch!

Was it helpful?

Solution

The chomp is made on a copy of $_, so it should not affect the socket handle at all. More likely, the removal of the newline is making your print statement wait in the buffer, and execute once the script is terminated.

In other words: It's not an error, just a delay.

Try using autoflush to execute the print immediately.

$| = 1;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top