Как использовать Perl File:: Temp?
Я хотел бы создать временный файл, записать в файл-дескриптор, затем вызвать внешнюю программу с именем файла.
Проблема в том, что я обычно хотел бы close
файла после его записи и перед вызовом внешней программы, но если я правильно понял close
-ing a tempfile()
, он должен быть удален.
Итак, какое решение здесь?
Ответы
Ответ 1
Запись в файл temp с отключенной буферизацией. Перед закрытием файла в Perl script вызовите внешнюю программу, и внешняя программа сможет прочитать все, что вы написали.
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
Ответ 2
Из 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.
Попробуйте установить его на 0
.
Ответ 3
с интерфейсом OOP File::Temp
вы можете сделать:
my $cpp = File::Temp->new;
print $cpp "SOME TEXT";
$cpp->flush;
`cat $cpp`;