Use the new_tmpfile class method from the IO::File module to get a filehandle opened for reading and writing. Use this if you don't need to know the file's name.

Code

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

Or you can use the tmpnam function from the POSIX module to get a filename that you then open yourself. Use this if you do need to know the file's name.

Code

use Fcntl; use POSIX qw(tmpnam);

# try new temporary filenames until we get one that didn't already # exist; the check should be unnecessary, but you can't be too careful do { $name = tmpnam() } until sysopen(FH, $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 ...

If you're committed to doing this by hand, use the process ID and/or the current time-value. If you need to have many temporary files in one process, use a counter: