views:

66

answers:

2

I would like to create a temp file, write to the file-handle then call an external program with the filename.

The problem is I would normally want to close the file after writing to it and before calling the external program, but if I understand correctly close-ing a tempfile() causes it to be removed.

So what is the solution here?

+4  A: 

From http://perldoc.perl.org/File/Temp.html:

unlink_on_destroy

Control whether the file is unlinked when the object goes out of scope. The file is removed if this value is true and $KEEP_ALL is not.

   1. $fh->unlink_on_destroy( 1 );

Default is for the file to be removed.

Try to set it to 0.

eumiro
+2  A: 

Write to the temp file with buffering turned off. Call the external program before you close the file in the Perl script, and the external program will be able to read everything you have written.

use File::Temp qw(tempfile);
use IO::Handle;

my ($fh, $filename) = tempfile( $template, ... );

... make some writes to $fh ...

# flush  but don't  close  $fh  before launching external command
$fh->flush;
system("/path/to/the/externalCommand --input $filename");

close $fh;
# file is erased when $fh goes out of scope
mobrule
I have a uncontrollable repulsion from using open files... but this seems to work.
David B