3

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!

TLP
  • 66,756
  • 10
  • 92
  • 149
John Frost
  • 673
  • 1
  • 10
  • 24

1 Answers1

5

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;
TLP
  • 66,756
  • 10
  • 92
  • 149
  • Ok, so what i found out is that when i do print $message."\n"; it works. Is it related to this? – John Frost Dec 28 '11 at 15:24
  • Thanks for the answer, your solution worked. Im wondering now, will it work with other loops to do processing as well? – John Frost Dec 28 '11 at 15:26
  • 1
    @JamieFlowers When you `print` something, it is sent to a print buffer in the shell. This buffer is not actually printed until a newline appears. It's not an actual error, just a delay. – TLP Dec 28 '11 at 15:30
  • @JamieFlowers - As you found out, your OS flushes the print buffer when you send it a NL character. Otherwise, the print buffer waits until it is full or it receives a NL character. Setting `$|` tells the print buffer to empty out immediately. I now `use feature qw(say);` and then use `say` instead of `print`. The `say` command is like `print` except it assumes an ending NL. – David W. Dec 28 '11 at 16:33