in reply to optimize the code
Code optimisation is always easier if you can properly compare the speed of different approaches, sometimes there are suprising results - see Benchmark and Devel::NYTProf. The second is a very good code profiler and might help, but in your case optimising the IO seems the important thing, comparing the different approaches and checking that 'improvements' actually *improve the running speed* with benchmarking is the best approach. Hope this helps.
Just a something something...