Have you considered using
Text::CSV_XS for your manipulation and writing out of the CSV?
Text::CSV_XS comes with a method for writing your resultant CSV database back out to a file (or filehandle).
You can also consider treating it like an SQL db with DBD::CSV depending on you familiarity with SQL.