in reply to error handling with dbi
You are calling undef() on your DB handle, rather than testing to see if it's defined.
Try changing:
if ( undef $dbh ) { [download]
if ( not defined $dbh ) { [download]