tempfile#

Create a temporary file and return an open filehandle paired with its filename.

Synopsis#

my ($fh, $filename) = tempfile();
my ($fh, $filename) = tempfile($template, DIR => $dir, SUFFIX => '.dat');
my $fh              = tempfile();                 # scalar context, file auto-unlinked

What you get back#

In list context, a two-element list ($fh, $filename): $fh is an open read/write filehandle on the new file and $filename is the path on disk. In scalar context, only the filehandle is returned and the file is unlinked immediately — the fd keeps the storage alive until $fh is closed.

Options#

  • DIR => $dir — directory to create the file in.

  • TMPDIR => 1 — place the file under the system temp directory.

  • SUFFIX => $ext — appended to the template; preserved across random fill.

  • UNLINK => 1 — register the file for deletion at interpreter exit.

  • OPEN => 0 — only pick a name; return (undef, $filename).

  • PERMS => 0o600 — explicit file permissions (default 0600).

A leading template argument (odd arg count) is accepted and must end in at least four X characters.

Examples#

use File::Temp qw/ tempfile /;
my ($fh, $name) = tempfile();
print $fh "hello\n";                        # writes to $name
my ($fh, $name) = tempfile('dataXXXXXX', DIR => '/var/tmp', SUFFIX => '.log');

## $name looks like /var/tmp/dataAb3c9F.log
my ($fh, $name) = tempfile('reportXXXXXX', UNLINK => 1);

## file is removed when the process exits

Edge cases#

  • Called as File::Temp->tempfile (method form): croaks.

  • Template with fewer than four trailing X characters: croaks.

  • Parent directory missing: croaks with a descriptive message.

Differences from upstream#

Fully compatible with upstream File::Temp 0.2312.

See also#

  • tempdir — directory counterpart with the same option vocabulary.

  • File::Temp->new — OO form that unlinks on object destruction.

  • mkstemp — low-level template-only variant without keyword options.

  • tmpfile — scalar-only form guaranteeing immediate unlink.