Three ways to use Perl to open a temporary 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]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值