问题 我该如何使用Perl的File :: Temp?


我想创建一个临时文件,写入文件句柄然后用文件名调用外部程序。

问题是我通常想要的 close 写入之后和调用外部程序之前的文件,但如果我理解正确的话 close - 一个 tempfile() 导致它被删除。

那么这里的解决方案是什么?


13141
2017-10-18 13:16


起源

听起来你实际上并不想要一个 临时 文件。 - brian d foy
但是我愿意。我在我的脚本中调用外部程序。完成后,我不再需要该文件了。 - David B


答案:


在关闭缓冲的情况下写入临时文件。在Perl脚本中关闭文件之前调用外部程序,外部程序将能够读取您编写的所有内容。

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

7
2017-10-18 13:24



我对使用打开的文件有一种无法控制的排斥......但这似乎有效。 - David B
哪里 $template 定义和定义的内容:甚至不是官方文档 File::Temp 提到这个难以捉摸的废话。 - Alexej Magura
它是任何字符串 以。。结束  连续4次或更多次 X的 - mob


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


5
2017-10-18 13:22





与OOP接口 File::Temp 你可以做:

my $cpp =  File::Temp->new;
print $cpp "SOME TEXT";
$cpp->flush;

`cat $cpp`;

0
2017-12-29 16:56