in reply to correcting output

How are you writing those records?

You should probably collect all the data in a hash, then print it all at once in one place. You can make sure you've got a CRLF at the end of every record that way by looking at the print function.