You call the finish() method on the statement handler within both your loops:
while($ref = $sth1->fetchrow_hashref) {
print FHExtract join (", ", values %$ref), "\n";
# Closing the statement handler
$sth1->finish;
}
and
while($ref1 = $sth2->fetchrow_hashref) {
print FHExtract join (", ", values %$ref1), "\n";
# Closing the statement handler
$sth2->finish;
}
You need to move those calls outside the loop, or rather, as the
docs recommend, don't use them at all - the statement handler going out of context does the same thing.