Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sleep in a while loop caused no response

Tags:

perl

I wrote a sleep in a while loop. It's a very simple code but didn't work.


use strict;
use warnings;

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

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

If commenting out #1, "go~" is printed; otherwise, it is just waiting without any "go~" to print. My intention is to do something periodically.

Could anyone give some explanation/hint?

like image 250
Steel Avatar asked Apr 25 '14 02:04

Steel


1 Answers

Try adding new line after go~

    use strict;
    use warnings;

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

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

Explanation why it works: The stdout stream is buffered, so will only display what's in the buffer after it reaches a newline (or when it's told to). You didn't use newline so the the text will get appended to buffer until the size of buffer.

If you don't want to use newline than add following lines at begining

use IO::Handle;
STDOUT->autoflush(1);
like image 92
coder hacker Avatar answered Oct 09 '22 18:10

coder hacker