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

Hi Monks

There is any (easy way) to add a delay into a foreach loop (elaborate each element of the array after x time)? The following of course doesn't work.

#!/usr/bin/perl -w use strict; foreach (1..20) { print "a"; sleep (1);#between each element of the array there should be 1 sec +ond interval } print "\n";

Replies are listed 'Best First'.
Re: Foreach time delay
by Corion (Patriarch) on Mar 16, 2017 at 10:49 UTC

    The above works, but you are Suffering from Buffering.

    Set autoflush if you want output to STDOUT to appear unbuffered:

    $| = 1;

    Alternatively, print newlines:

    foreach (1..20) { print "a\n"; sleep (1);#between each element of the array there should be 1 sec +ond interval }

      Thanks Corion, you opend a new world for me. Fantastic!

      A reply falls below the community's threshold of quality. You may see it by logging in.
      Is there any good reason why we're still line-buffering stdout? It seems like a throwback to the timesharing days. This is the 21st century, people!
        Yes there is:

        "If Perl made a system call for every read operation, that would be 10,001 system calls in all (one extra to detect end-of-file), and if the file was on the disk, it would have to wait for the disk at least 10,000 times. That would be very slow."

        Can you write a better OS?