in reply to print() on closed filehandle

Always check the return value of calls to open. The idomatic way to do that would be
open (OUTPUT_FILE, ">$outputfile") or die "Could not open $outputfile: + $!";
(same for FLAT_FILE, and anything else you open.) That form is great for debugging ($! will contain the actual error message if there's a problem), but you might want to replace the die with something more robust if you need to recover from the error. Once you find out why your file isn't opening, you can proceed to fix it.