This is something best done with a module which is heavily tested, tries to account for all corner cases and automatically cleans up after itself.
Almost verbatim from the synopsis:
use File::Temp;# Generate a temp file in a temp dirmy ($filename0,$filehandle0) = tempfile;# specify a template for the filename# * are replaced with random charactersmy ($filename1,$filehandle1) = tempfile("******");# Automatically unlink files at DESTROY (this is the default)my ($filename2,$filehandle2) = tempfile("******", :unlink);# Specify the directory where the tempfile will be createdmy ($filename3,$filehandle3) = tempfile(:tempdir("/path/to/my/dir"));# don't unlink this onemy ($filename4,$filehandle4) = tempfile(:tempdir('.'), :!unlink);# specify a prefix, a suffix, or both for the filenamemy ($filename5,$filehandle5) = tempfile(:prefix('foo'), :suffix(".txt"));