I tried to help only with Perl features that would contribute to a solution... The sort of thing not obvious if you're, say, a 'C' programmer. The first poster nearly had the packing piece.
...if you think the fragments of code I posted are a complete solution, then you don't know the scale of the problem :-)