Three ways to use Perl to open a temporary file

來源:互聯網
上載者:User

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]

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.