5

I have the following code to print a "." each second to simulate a progress bar.

$num = 15;
while($num--){
    sleep(1);
    print ".";
}

The problem I'm having now is the "." character is not printed after each loop. Instead, all 15 "." are printed at once after the loop exits. However if I print ".\n", it works fine. But the "." will be printed on a new line every time which is not what I want.

It seems quite weird and could not figure out why. Could anyone provide some help? Thank you.

Regards, Allen

Allen Qin
  • 19,507
  • 8
  • 51
  • 67

3 Answers3

21

That's probably because I/O is being buffered. Try disabling buffering (autoflush):

$| = 1;

before your loop.

For a more complete explanation, refer to How do I flush/unbuffer an output filehandle? Why must I do this?

Mat
  • 202,337
  • 40
  • 393
  • 406
  • Thank you Mat, this works great! I will have a read of the article you recommended. I'm amazed by the rapidity of the answering of my question. I was expecting to get an answer before I go to bed tonight. – Allen Qin Apr 17 '11 at 12:05
4

You need to disable buffering on STDOUT. See $| in perlfaq

aschepler
  • 70,891
  • 9
  • 107
  • 161
1

The standard output stream is usually buffered. Try flushing the output stream after each print statement. See the Perl Cookbook, §7.13 for a detailed explanation and solution.

Philip
  • 5,795
  • 3
  • 33
  • 68