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

Hey Gr8 ppl,

        I have written a piece of code to print the file contents. Here is the code,

#!/usr/bin/perl -w use strict; open FILEHANDLE , "$filename" or die "cannot open the file : $filename + :$!"; my @array = <FILEHANDLE>; foreach ( @array ) { chomp $_; #This Chomp plays an important role here; sleep 1; print "$_"; #But this line does some thing strange. } close FILEHANDLE ;

In the above code, If i comment the

chomp $_;

    The sleep function executes first then it prints the contents of the file. But where as if I uncomment the line, (i.e) i didn't remove the new line char at the end of the file contents, it is doing good. Can you ppl able to guess why it does so ? Nowhere they have mentioned about sleep's this behavious. What may be the relation ship with the sleep and the newline entry ?



Thanks in advance.



Regards,
S.Venni Rajan.
"A Flair For Excellence."
                -- BK Systems.

Replies are listed 'Best First'.
Re: What is the wrong with the sleep function ?
by Aristotle (Chancellor) on Dec 30, 2005 at 09:11 UTC

    You are Suffering from Buffering. Read that article for enlightenment, it will explain all.

    Makeshifts last the longest.

Re: What is the wrong with the sleep function ?
by TedPride (Priest) on Dec 30, 2005 at 09:32 UTC
    With buffering on, output is only actually printed to the screen whenever a line finishes. So when you leave the \n in, everything is fine, but if you remove it, everything is buffered until the very end.
    for (1..10) { print '.'; sleep 1; } $| = 1; # Turn off buffering for (1..10) { print '.'; sleep 1; }
Re: What is the wrong with the sleep function ?
by runrig (Abbot) on Dec 30, 2005 at 09:13 UTC
    See $| (aka OUTPUT_AUTOFLUSH) in perlvar. It is buffering the output. set $| to a true value if you don't want output to buffer.