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

I need to create a temp file. Here's my straightforward code:
my $fh = File::Temp->new(); $fh->autoflush(1); foreach my $cmd (@_) { print "$cmd\n"; print $fh "$cmd\n"; } system "dir $fh";
When I run it, I get this:
C:> supportsave -n -h -d /incoming/50798070 -l ftp exit Volume in drive C has no label. Volume Serial Number is 32B6-C79A Directory of C:\DOCUME~1\dentos\LOCALS~1\Temp 11/30/2012 05:16 PM 0 vfmhcyNzQN 1 File(s) 0 bytes 0 Dir(s) 783,720,448 bytes free
Why is my file showing up with zero bytes? I've tried using flush at the end of the loop, and sleeping 10 seconds for the OS to catch up, but it keeps acting the same. Did I miss something obvious in the docs? Many thanks for any assistance.

Replies are listed 'Best First'.
Re: File::Temp acting strange under Windows XP (close)
by tye (Sage) on Dec 01, 2012 at 01:02 UTC

    The size of the file in the directory entry is not always updated after each write to the file, even if the bytes written get flushed to disk. I download GB files and sometimes I see partial size updates but often the file size shows as 0 until the very end (presumably due to the file handle having been closed).

    - tye        

      Unfortunately, running system "type $fh"; doesn't produce any output, and I need a temp file that I can pass by name to an external command (putty -m) that doesn't accept open file handles or anything.

      Google turned up this bit of disappointing information: To ensure that the right amount of flushing occurs, the cache manager spawns a process every second called a lazy writer. The lazy writer process queues one-eighth of the pages that have not been flushed recently to be written to disk. It constantly reevaluates the amount of data being flushed for optimal system performance, and if more data needs to be written it queues more data. Lazy writers do not flush temporary files, because the assumption is that they will be deleted by the application or system. --

      Maybe I need to skip File::Temp and just create my own "normal" file with a random name (e.g. "file.$$").

Re: File::Temp acting strange under Windows XP
by Kenosis (Priest) on Dec 01, 2012 at 00:14 UTC

    Your script produced similar results under Win7 when I ran it. However, the following ran equally well on Win7 and Lunix:

    use warnings; use strict; use File::Temp qw/tempfile/; my $fh = File::Temp->new(); print "$_\n" for 0 .. 4; $fh->seek( 0, 0 ); print for <$fh>; close $fh


    0 1 2 3 4

    IO::File's new_tmpfile can also be used like File::Temp--in case it may work better for you:

    ... use IO::File; my $fh = IO::File->new_tmpfile or die $!; ...