in reply to how to improve this?

First you have to know wich part of the program is slow. Is it the DB query? Or the output? or the perl code itself?

To find the bottleneck I'd recommend reading the thread RFC: Profiling your code..

When you know which part is the slowest one you can start to optimize it. But don't guess, you'll be wrong (usually).