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

时间:2010-10-18 13:16:56

标签: perl temporary-files

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

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

那么解决方案是什么?

4 个答案:

答案 0 :(得分:9)

在关闭缓冲的情况下写入临时文件。在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

答案 1 :(得分:6)

来自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

答案 2 :(得分:0)

使用File::Temp的OOP接口,你可以这样做:

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

`cat $cpp`;

答案 3 :(得分:0)

由于可能出现死锁,所以关闭比刷新更好。 File :: Temp tempfile用锁打开

{
    my $tmp = File::Temp->new(
        UNLINK => 0
    );

    select $tmp;
    say 123;
    select STDOUT;

    # $tmp->flush;
    close $tmp;

    say 'slurp >> ', path($tmp->filename)->slurp;
}

{
    my $tmp = Path::Tiny->tempfile(
        UNLINK => 0
    );

    my $fh = $tmp->filehandle('+>');

    select $fh;
    say 123;
    select STDOUT;

    # $fh->flush;
    close $fh;

    say 'slurp >> ', $tmp->slurp;
}
相关问题