Here I'll summarize three ways to open a temporary file using Perl.
The first way is to create the new object via module IO::File to get a read/write file handle as below.
my $temp_fh = IO::File->new_tmpfile;
Perl closes these files when the scalar variable goes out of scope. If that's no enough, we can do it ourselves explicitly by either calling close or undefining the file handle:
$temp_fh->close or die "Could not close file: $!";
Or,
undef $append_fh;
The second way: Perl v5.6 and later can open an anonymous temporary file if we give it undef as a filename. We probably want to both read and write from that file at the same time. Otherwise, it's a bit pointless to have a file we can't find later:
open my $fh, '+>', undef
or die "Could not open temp file: $!";
The third way: using the module File::Temp maybe a standard way to create a named temporary file. We can create temporary file or directory as following code.
use File::Temp qw(tempfile tempdir)
my ($fh, $file_name) = tempfile();
my ($temp_dir) = tempdir( CLEANUP => 1);
Notice that File::Temp will open temporary file with binary mode, so if you want to work with a text file, use binmode to mark FILEHANDLE as a specific encoding. For example.
binmode FILEHANDLE ':utf8';
See Also
1. Creating Temporary Files in "Perl Cookbook" http://docstore.mik.ua/orelly/perl4/cook/ch07_12.htm
[END]
本文介绍了使用Perl语言创建临时文件的三种方法:通过模块IO::File新建对象、使用匿名临时文件名打开文件以及利用模块File::Temp创建命名临时文件,并强调了文件关闭和编码标记的重要性。

被折叠的 条评论
为什么被折叠?



