简体   繁体   English

使用chomp()时打印失败

[英]Print fails when using chomp()

So I have this problem while looping through a socket with a while loop. 所以我在使用while循环遍历套接字时遇到了这个问题。

When I use this, it totally works fine but I have newlines on every $message , which I don't want. 当我使用它时,它完全正常,但我对每条$message都有换行符,这是我不想要的。

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). 但是当我添加chomp时,循环仅在我断开客户端时完成(我理解为什么)。 My guess is that chomp removes the newline from the $_ variable and thus the loop will not work anymore. 我的猜测是chomp从$_变量中删除了换行符,因此循环将不再起作用。

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! 谢谢你!

The chomp is made on a copy of $_ , so it should not affect the socket handle at all. chomp是在$_的副本上制作的,所以它根本不应该影响套接字句柄。 More likely, the removal of the newline is making your print statement wait in the buffer, and execute once the script is terminated. 更有可能的是,删除换行符会使您的print语句在缓冲区中等待,并在脚本终止后执行。

In other words: It's not an error, just a delay. 换句话说:这不是错误,只是延迟。

Try using autoflush to execute the print immediately. 尝试使用autoflush立即执行打印。

$| = 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM