Disclaimer first - I am no expert, and this is just a hunch...
Perl complains about needing an explicit package name for a global symbol
I suspect the issue is with the big if and and more specifically with the scope of the variables that Perl is complaining about. You might be trying to access these variables outside of the scope (i.e. enclosing block) in which you defined them. I checked the code, trying to see if I could catch the problem with the blocks but I don't see it. You might want to explore this in the meantime as the experts reply (if your are in a crunch) Good luck!.