in reply to Failed to close file

Try printing $! in your error message and see what it says. Also check for errors in print (and make sure to print $! in that case, too).