Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am running into a problem trying to print a notification periodically while a script is running so the user can visually verify that the script is actively running. I can run the following code that I found in the Q&A sections and it works as expected:
use strict; my $tick = "tick\n"; # loop until this process is terminated from the outside while (1) { print $tick; # Make "tick" into "tock" and "tock" into "tick" $tick =~ tr/io/oi/; # sleep 10 seconds sleep( 10 ); }
Which prints a tick or tock every 10 seconds. The following code does not function as expected, to illustrate the same problem I am having:
use strict; foreach (1..10) { print '*'; sleep(1); }
This will pause for 10 seconds and then print 10 *'s instead of printing a * every second. Seems like perl is optimizing the code somehow. Any ideas?

Replies are listed 'Best First'.
Re: Optimization problem?
by moritz (Cardinal) on May 06, 2008 at 12:19 UTC
Re: Optimization problem?
by mscharrer (Hermit) on May 06, 2008 at 12:40 UTC
Re: Optimization problem?
by Burak (Chaplain) on May 06, 2008 at 12:19 UTC
    you need to disable buffering:
    $| = 1;