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

Monks,

I am creating a new file and then using print in a loop to write lines of text to a file. However, I am also then checking to see if any lines have previously been written to that file using -s. This test always says that the file is zero size even if I have just used print to write a line into it. When I check the file it is indeed empty until the script has finished when there are multiple lines in the file.

What I want to know is, does print only write to the file once the filehandle is closed? How can I write data into a file and (before closing it) test to see if data has already been written?

Many thanks for your help,

Marc

  • Comment on Does print() write immediately to a file?

Replies are listed 'Best First'.
Re: Does print() write immediately to a file?
by Abigail-II (Bishop) on Oct 15, 2003 at 12:41 UTC
    Others have suggested to unbuffer your writes, but unbuffered writes often make that your program is accessing the disk far more often, slowing down the entire box.

    Instead of using '-s', you can find the length of the file also by seeking to the end, then using tell. No unbuffering needed. Here's an example program:

    #!/usr/bin/perl use strict; use warnings; use Fcntl qw /:seek/; my $file = "/tmp/flup"; open my $fh => "> /tmp/flup" or die; print $fh "Some line of text\n"; my $l0 = -s $file; # General concept, assuming the filepointer can be anywhere. # If you know the file pointer is at the end, a simple tell() # will do, and no seeking at all is necessary. my $old = tell $fh or die "tell: $!"; seek $fh, 0, SEEK_END or die "seek: $!"; my $l1 = tell $fh; die "Nothing in file!\n" unless $l1; seek $fh, $old, SEEK_SET or die "seek: $!"; print "-s $file: $l0. seek: $l1\n"; __END__ -s /tmp/flup: 0. seek: 18

    Abigail

Re: Does print() write immediately to a file?
by robartes (Priest) on Oct 15, 2003 at 11:36 UTC
    This is a FAQ. Basically, you need to set $| to true for your filehandle. This is a funky way of doing so, straight from the FAQ:
    select((select(OUTPUT_HANDLE), $| = 1)[0]);

    CU
    Robartes-

      Thank you so much. This works great!
Re: Does print() write immediately to a file?
by ctilmes (Vicar) on Oct 15, 2003 at 11:36 UTC