2

I think I've read how to do this somewhere but I can't find where. Maybe it's only possible in new(ish) versions of Perl. I am using 5.14.2:

I have a Perl script that writes down results into a file if certain criteria are met. It's more logical given the structure of the script to write down the results and later on check if the criteria to save the results into a file are met.

I think I've read somewhere that I can write content into a filehandle, which in Linux I guess will correspond to a temporary file or a pipe of some sorts, and then give the name to that file, including the directory where it should be, later on. If not, the content will be discarded when the script finishes.

Other than faffing around temporary files and deleting them manually, is there a straightforward way of doing this in Perl?

4

2 回答 2

6

您所描述的内容没有简单的(UNIX)工具,但行为可以由基本的系统操作组成。Perl 的 File::Temp 已经完成了你想要的大部分工作:

use File:Temp;

my $tmp = File::Temp->new;      # Will be unlinked at end of program.

while ($work_to_do) {
  print $tmp a_lot_of_stuff();  # $tmp is a filehandle
}

if ($save_it) {
  rename($tmp, $new_file);      # $tmp is also a string.  Move (rename) the file.
}                               # If you need this to work across filesystems, you
                                # might want to ``use File::Copy qw(move)'' instead.

exit;                           # $tmp will be unlinked here if it was not renamed
于 2013-07-30T17:27:37.753 回答
1

我为此使用 File::Temp 。

但是您应该记住 File::Temp 默认情况下会删除该文件。没关系,但在我的情况下,我在调试时不希望这样。如果脚本终止并且输出不是所需的,我无法检查临时文件。

所以我更喜欢设置$KEEP_ALL=1$fh->unlink_on_destroy( 0 );当OO或($fh, $filename) = tempfile($template, UNLINK => 0);然后自己取消链接文件或移动到适当的位置。

在关闭文件句柄后移动文件会更安全(以防万一有一些缓冲发生)。因此,我更喜欢一种默认情况下不删除临时文件的方法,然后在完成所有操作后,设置一个条件,将其删除或将其移动到您想要的位置和名称。

于 2013-07-31T23:18:34.143 回答