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

How can I force Perl to write the information in buffer to harddisk. I have used "$| = 1" but it does not help. The problem is quite urgent as the 1/20 part of the work stores already over 500 MB in my swapfile. Thank you in advance.
  • Comment on How to force Perl to write imediately on harddisk?

Replies are listed 'Best First'.
Re: How to force Perl to write imediately on harddisk?
by ikegami (Patriarch) on Sep 07, 2005 at 18:34 UTC

    You need to select the file handle that needs to be flushed before using $|=1.

    sub flush { my $h = select($_[0]); my $af=$|; $|=1; $|=$af; select($h); } sub autoflush { my $h = select($_[0]); $|=$_[1]; select($h); } # Flush immediately without turning auto-flush on: flush(*FILE); flush(\*FILE); flush($fh); # Flush immediately and turn auto-flush on: autoflush(*FILE, 1); autoflush(\*FILE, 1); autoflush($fh, 1); # Turn auto-flush off: autoflush(*FILE, 0); autoflush(\*FILE, 0); autoflush($fh, 0);

    Alternatively, if your file handle is an IO::Handle (or subclass) object, IO::Handle already provides methods:

    # Flush immediately without turning auto-flush on: $io->flush(); # Flush immediately and turn auto-flush on: $io->autoflush(1); # Turn auto-flush off: $io->autoflush(0);
Re: How to force Perl to write imediately on harddisk?
by sh1tn (Priest) on Sep 07, 2005 at 18:37 UTC
      $| = 1, select $_ for select OUTPUT_HANDLE; before each critical print does the work... Ty
Re: How to force Perl to write imediately on harddisk?
by eff_i_g (Curate) on Sep 07, 2005 at 18:35 UTC
    try this perhaps?

    use IO::Handle; STDOUT->autoflush(1);
      Thank you for the fast answers. I am sorry but the code is about 500 lines long. I can describe what it does. A special file will be downloaded, then I gather information from this file. With this information I connect to a server and post several ten thousad of times special coordinates to it in order to get special files back. These will be stored on hard disk and proccess further. From all these files another kind of information will be written to four different files as a short report. And here is the problem. These files are empty. I have tested the programm on a short file and it works fine. My problem is that I have to flush all this information on hard disk. I will try as suggested to select the filehandle that has to be flushed because I dont work with file:IO. Thank you again. If I have some more problems I will be back soon. :)
Re: How to force Perl to write imediately on harddisk?
by Anonymous Monk on Sep 07, 2005 at 18:47 UTC
    Although this doesn't solve your question, anyone who is actually interested in forcing "Perl to write immediately to harddisk" should look at File::Sync and fsync.
Re: How to force Perl to write imediately on harddisk?
by kwaping (Priest) on Sep 07, 2005 at 18:33 UTC
    Can you please provide the code for review, if possible?