O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required