Unsurprisingly, there's already a module on CPAN to handle the temp-file maneuvers:
use IO::AtomicFile;
# Write a temp file, and have it install itself when closed:
my $FH = IO::AtomicFile->open("bar.dat", "w");
print $FH "Hello!\n";
$FH->close || die "couldn't install atomic file: $!";