use File::Copy qw(cp); open(FILE, ">$target") or do { cp "$target", "$target~temp1"; unlink "$target"; rename "$target~temp1", "$target"; }; close( FILE );