Thank you so much for taking the time to explain this code. There was a lot in there that i couldn't get my head around, so your explanation is very much appreciated. I'm actually now using the code so it's good that i now know how it works!!
A final point, i tried to move the subroutine definition below the code calling it (I like to keep all my subs at the bottom), but i get an error:
Can't call method "nForX" without a package or object reference at ./test.pl line 617.
Is there a reason for this? And how do i store the sub somewhere else?