加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Three ways to use Perl to open a temporary file

发布时间:2020-12-15 20:58:31 所属栏目:大数据 来源:网络整理
导读: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 file

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]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读