my $pull1 = "SELECT id, seq from table"; my $pull2 = "SELECT id, seq from table where table.id in(long string of nested "in" criteria); my $sql1 = $lib_dbh->selectall_arrayref($pull1); my $sql2 = $lib_dbh->selectall_arrayref($pull2); foreach my $sql1 (@{$sql1}) { $table1{$sql1->[1]}{$sql1->[0]}=undef; } foreach my $sql2 (@{$sql2}) { $table2{$sql2->[1]}{$sql2->[0]}=undef; } my @bases = ('A','C','G','T'); Label: foreach my $x (keys %table1){ if (exists $table2 ({$x})) { my $found_alt = 0; my @storage_array = (); @{$storage_array[1]} = keys %{$table1{$x}}; foreach my $bases (@bases) { my $alt = $x; substr($alt, 6, 1) = $opt; next if ($alt eq $x); if (exists $table1{$alt}) { $found_alt = 1; push @{$storage_array[2]}, keys %{$table1{$alt}}; } } next Label unless ($found_alt ); #continues to follow on script.