It would help if you told us what you were seeing as a problem. Also, things like what version of Perl, what OS, and what the basic purpose of what you're doing ...
The most obvious problem I'm seeing is that $sql is defined well after any time you use it.
A few helpful pointers:
- use strict and warnings. They will help catch a number of silly errors/typos that a human cannot see.
- Try using print as a debugging tool. I notice you use $sql a lot. Are you sure you know what its value is at any given point?
------
We are the carpenters and bricklayers of the Information Age.
Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.