in reply to Running two loops

It might be easier if print your output to a file rather than use STDOUT. If you
use strict; use warnings;
and declare all the variables then you may get some useful information on what is actually happening.

It would certainly be easier to help you.