Creating Temporary Files

Problem

You need to create a temporary file and have it automatically deleted when your program exits. For instance, you want to write a temporary configuration file to feed a program you launch. In this case, you want to know the temporary file’s name to tell the utility program. In other cases, you may just want a temporary file to write to and read from, and don’t need to know its filename.

Solution

If you don’t need to know the file’s name, use the new_tmpfile class method from the IO::File module to get a filehandle opened for reading and writing:

use IO::File;

$fh = IO::File->new_tmpfile
        or die "Unable to make new temporary file: $!";

If you need to know the file’s name, use the tmpnam function from the POSIX module to get a filename that you then open yourself:

use IO::File;
use POSIX qw(tmpnam);

# try new temporary filenames until we get one that didn't already exist
do { $name = tmpnam() }
    until $fh = IO::File->new($name, O_RDWR|O_CREAT|O_EXCL);

# install atexit-style handler so that when we exit or die,
# we automatically delete this temporary file
END { unlink($name) or die "Couldn't unlink $name : $!" }

# now go on to use the file ...

Discussion

If you only need scratch space, the IO::File module’s new_tmpfile class method returns a filehandle connected to a temporary file that’s been opened read-write by using the following code:

for (;;) {
    $name = tmpnam();
    sysopen(TMP, $tmpnam, O_RDWR | O_CREAT | O_EXCL) && last;
}
unlink $tmpnam;

This file will ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.