in reply to Loop counter only works for 2

Uhm.. oh dear :---)

From just a quick glance at your code:

You should really check out Mark-Jason Dominus's excellent program repair shop series on www.perl.com. There is some very helpful advice there to get you started on writing better Perl.