# replace exit(0); with: exit(close(DATA)); # or (at beginning of script) sub exit_script { close(DATA); exit(0); } # then replace your exit calls with exit_script;