Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I use Perl's File::Temp?

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?

like image 680
David B Avatar asked Oct 18 '10 13:10

David B


People also ask

How do I open temporary temp files?

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.

When should you use temp files?

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.

Where do you put temp files?

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.


2 Answers

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
like image 119
mob Avatar answered Oct 19 '22 19:10

mob


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.

like image 26
eumiro Avatar answered Oct 19 '22 21:10

eumiro