It's too early here to read all your code ( :P ), but I see you're using a AoA. If you have to perform any kind of match against it, you can gain a lot of performance by changing it to a HoA (Hash of arrays). With that, you have "direct" acces to the key and you don't have to search the entire array. See
for more info. Also, you should loop only once and write each line to the appropiate file.