Hi
Griegomas,
this does not relate directly to your question, but I would really suggest that you indent your code much more consistently. The way the code is laid-out right now is almost unreadable, or at least very difficult to follow both for us, poor monks, and for yourself. I can guarantee that you will save a lot of debugging time by taking the little time that is required to format your code properly.
If needed you could use a code prettifier, such as Perltidy, a Perl script which indents and reformats Perl scripts to make them easier to read.