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?
Find where your temp files are stored by pressing and holding the Windows button, and then hit R to bring up the Run dialogue box. Type temp and press Enter (or click OK) to open up the folder location and see your temp files. Hold Ctrl and click individual items to select them for cleanup.
Temporary files are needed when you are using programs or applications, as this is when additional storage must be created to accommodate extra memory and existing file usage. Often, temporary files are created when you are running computer programs which consume large amounts of data.
Most programs will create temp files in a folder called C:\Users\AppData\Local\Temp — that's likely where your computer stores the majority of your temporary files. It's safe to empty out the AppData\Local\Temp folder and delete the temp files you find there.
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With