Roland Turner

about | contact

Safe creation of tempfiles

These are safe against accidental conflict; deliberate conflicts may or may not be covered:

use File::Temp qw/ tempfile tempdir /;

($fh, $filename) = tempfile(“foo.XXXXXXXXXX”, DIR => File::Spec->tmpdir());


/bin/mktemp -t foo.XXXXXXXXXX



The risk with /tmp/foo.$$ is the birthday paradox. For 16-bit PIDs, n ~= sqrt(2 * 65536 ln (1 / (1-0.5)) ~= 300, so a few hundred tempfiles lying around means that clashes are more likely to occur than not.