Perl: sleep in while loop did not cause any response

I am new to Perl. I wrote a dream in a while loop: this is very simple code, but it does not work. furstruted ...


use strict;
use warnings;

&main();
sub main()
{
print "hello\n";

while(1)                    # #1
{   
      print "go~  ";
      sleep 2;      
}
}

if you comment # 1, it prints "go ~"; otherwise, it just waits until there is a "go ~" to print. My intention is to periodically do something.

Can someone give some explanation / hint?

+4
source share
1 answer

Try adding a new line after the jump ~

    use strict;
    use warnings;

    &main();
    sub main()
    {
    print "hello\n";

    while(1)                    # #1
    {
          print "go~\n";
          sleep(2);
    }
    }

Explanation of why this works: The stdout stream is buffered, so it will only display what is in the buffer after it reaches a new line (or when it was said). You did not use a new line so that the text is added to the buffer to the size of the buffer.

If you do not want to use a new line, than add the following lines at the beginning

use IO::Handle;
STDOUT->autoflush(1);
+8
source

Source: https://habr.com/ru/post/1537989/


All Articles