my $sth = $dbh->prepare( "SELECT pmid, abstract FROM PM_text " . "WHERE title LIKE '%E.coli%'" ); $sth->execute; my @text_refs = ($sth->fetchrow_hashref()); $sth->finish; ... for my $text_ref (@text_refs) { for my $cont_name (@cont_names) { if ($text_ref->{abstract} =~ m/$cont_name/im) { for my $bact_name (@bact_names) { if ($text_ref->{abstract} =~ m/$bact_name/im) { print "matched at text $text_ref->{pmid}, " . "for $cont_name and $bact_name\n"; $sth2->execute( $bact_name, $cont_name, $text_ref->{pmid} ); $sth3->execute( $cont_name, $text_ref->{pmid} ); } } } } }