Three ways to use Perl to open a temporary file

Source: Internet
Author: User

Here I'll summarize three ways to open a temporary file using Perl.

The first wayIs 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 "cocould 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 "cocould 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]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.