I'd suggest first reindenting your program so the structure is clear (use perltidy or the indenting feature of a [no such wiki, comparison of text editors] such as vim, emacs, etc).
Next, for a program as small as this one, pretend you're the computer, and simply do the operations one by one. If you're moderately careful, you'll find the bugs pretty easily as you'll find your program telling you to do things at the wrong time. Just take a sheet of paper and write a small simple data set on it at the top. Use the bottom to keep track of the values of variables and the output file. Then, as you find the bugs, repair them.
While I find desk work like that a bit relaxing, you'll find that more complex programs require far too much work to do by hand. That's when using the perl debugger comes in handy. Learn how to use it, and it will help you become a better programmer.
But for this program, it would be instructive if you do it by hand so you can get a feel for how to read a program and find errors. As an example, for the program:
My worksheet would look something like:
When your only tool is a hammer, all problems look like your thumb.
In reply to Re^3: to copy certain content in file & repeat it .