How do I make a temporary file name?

Use the File::Temp module, see File::Temp for more information.

  use File::Temp qw/ tempfile tempdir /; 
  $dir = tempdir( CLEANUP => 1 );
  ($fh, $filename) = tempfile( DIR => $dir );
  # or if you don't need to know the filename
  $fh = tempfile( DIR => $dir );
The File::Temp has been a standard module since Perl 5.6.1. If you don't have a modern enough Perl installed, use the new_tmpfile class method from the IO::File module to get a filehandle opened for reading and writing. Use it if you don't need to know the file's name:

    use IO::File;
    $fh = IO::File->new_tmpfile()
	or die "Unable to make new temporary file: $!";
If you're committed to creating a temporary file 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:

    BEGIN {
	use Fcntl;
	my $temp_dir = -d '/tmp' ? '/tmp' : $ENV{TMPDIR} || $ENV{TEMP};
	my $base_name = sprintf("%s/%d-%d-0000", $temp_dir, $$, time());
	sub temp_file {
	    local *FH;
	    my $count = 0;
	    until (defined(fileno(FH)) || $count++ > 100) {
		$base_name =~ s/-(\d+)$/"-" . (1 + $1)/e;
		sysopen(FH, $base_name, O_WRONLY|O_EXCL|O_CREAT);
	    }
	    if (defined(fileno(FH))
		return (*FH, $base_name);
	    } else {
		return ();
	    }
	}
    }

Back to perlfaq5