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

When in a while infinite loop, if I introduce a second delay during the print commands nothing gets written to the file handle. If I have no delay, everything gets written to the file handle. This works:
use strict; use warnings; my $log = "/tmp/log.txt"; open LOG, ">", $log or die "$!\n"; while ( 1 ) { my $time = localtime() ; print LOG "$time\n"; print "$time\n"; } close LOG;
Where as if I add  sleep 5; to the while loop, it prints the time to the screen, but nothing gets written to the file. I do not understand why. Any ideas? TIA

Replies are listed 'Best First'.
Re: problem writing to a file handle
by ikegami (Patriarch) on Jun 19, 2010 at 19:48 UTC

    The output is buffered and you didn't wait long enough. (4096b / 25b/msg * 5s/msg ≤ 164s)

    Buffering can be turned off:

    use strict; use warnings; use IO::Handle qw( ); my $log = "/tmp/log.txt"; open my $LOG, ">", $log or die "$!\n"; $LOG->autoflush(1); while ( 1 ) { my $time = localtime() ; print $LOG "$time\n"; print "$time\n"; } close $LOG;
Re: problem writing to a file handle
by Corion (Patriarch) on Jun 19, 2010 at 19:50 UTC

    Output to files is buffered. If you wait long enough, the output will also show up in the file.

    If you really want the output to be unbuffered (thus slowing down your program somewhat), see perlvar about $|:

    my $oldfh = select(LOG); $| = 1; select($oldfh);
Re: problem writing to a file handle
by biohisham (Priest) on Jun 20, 2010 at 16:49 UTC
    A very interesting relevant read is buffering from buffering, it discusses the various buffering mechanisms and contexts in Perl.


    Excellence is an Endeavor of Persistence. A Year-Old Monk :D .