Your script would be much quicker if you took the open and close statements out of the foreach (keys %key) loop.
Do those statements only once, and maintain your data in arrays. Disk operations should be minimal, and in your case you only need to read and write once.
--
bm