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

Hello monks,

I am testing a sleep functionality with in a for loop. I used "say" or "print" inside the for/foreach loop what ever you would like to call it.

Interesting thing is with "say" the printing is happening immediately for each element of the list where as for "print" function printing is happening all at once. In other words in below Example 1 for every 1 second it printed the number where as Example 2 printed all its output after 10 seconds.
Can anyone shed some light for this ignorant monk ??

Example 1:
perl -e 'use v5.10;for (1..10) {say $_; sleep(1);}'
1
2
3
4
5
6
7
8
9
10

Example 2:
perl -e 'use v5.10;for (1..10) {print $_; sleep(1);}'
12345678910

Regards,
Rookie Monk

Replies are listed 'Best First'.
Re: Print vs Say with sleep function
by choroba (Cardinal) on Jan 19, 2016 at 22:22 UTC
    Standard output is buffered. The buffer is flushed when a newline is encountered. To cancel buffering, try
    perl -we '$| = 1; for (1..10) { print $_; sleep 1;}'

    You can also call

    STDOUT->autoflush(1);

    with the same effect as setting the variable.

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
      Thank you Choroba. This helped me!
Re: Print vs Say with sleep function
by 1nickt (Canon) on Jan 19, 2016 at 22:20 UTC

    You can force print() to print unbuffered like this:

    $| = 1;
    perl -e 'use v5.10; $| = 1; for (1..10) {print $_; sleep(1);}'

    I was looking for a link to the docs to share with you and found this oldie but goodie from the Perl Cookbook: Recipe 7.19. Flushing Output :-)

    Hope this helps!

    update: Changed link to Perl Cookbook excerpt since the one I originally posted turned out to be to a pirate site! (Of course some might use the same description for Google Books ... but the ORA permission is right there.) I just thought it would be fun to post an example from a classic text; next time I'll stick to the current perldoc, I think.
    The way forward always starts with a minimal test.
      Thank you very much lnickt :-)
Re: Print vs Say with sleep function
by Mr. Muskrat (Canon) on Jan 19, 2016 at 22:24 UTC
Re: Print vs Say with sleep function
by Laurent_R (Canon) on Jan 19, 2016 at 23:02 UTC
    Just changing Example 2 to this should give you the same result as with say:
    $ perl -e 'use v5.10;for (1..10) {print "$_\n"; sleep(1);}' 1 2 3 4 5 6 7 8 9 10
    It is not even needed to deactivate buffering and change $|, since printing to STDOUT is line buffered (i.e. the buffer is flushed as soon as a newline character is found).
Re: Print vs Say with sleep function
by kcott (Archbishop) on Jan 20, 2016 at 07:48 UTC