As I had the same scenario, here is what I found after some reading and experimenting:
my $XML;
# ...
if ($XML) {
use File::Temp;
my $tf = File::Temp->new('TEMPLATE' => 'monXXXXXX', 'DIR' => '/tmp',
'SUFFIX' => '.xml');
$tf->print($XML);
# in reality a more complex command than "cat" is being used
$tf->close() and system(qw(/usr/bin/cat), $tf->filename());
# ...
}
The point here is that using $tf
after close
to get the filename, prevents the file from being deleted (i.e.: $tf
being garbage-collected and DESTROYed).
I don't need the temporary file any more after system
, so it's OK if it's removed after that call.
I theory Perl could garbage-collect $tf
immediately after the filename had been determined (and thus the external command would not find it any more), but that's not how Perl works.
If paranoid, you could pass $tf
to some function after system
, thus preventing garbage collection before...
File::Temp
does not unlink the file after creation (in contrast toIO::File->new_tmpfile
). – Orthicon