From your comments, it sounds like you're unhappy with this loop?
# here is where I messed up for the query. I cannot control this loop.
# it finds the things but fails to print them only once.
foreach $1 (sort keys %file1){
foreach my $position1 (@{$file1{$1}}){
$found =0;
foreach $contig_id(sort keys %hash_1){
foreach my $position (@{$hash_1{$contig_id}}){
$found = 1 if $1 =~ /^$contig_id/ && $contig_id=~ /^$1
+/ && $position1==$position;
print RESULTS "$position1\t$1\n" if $found;
print "not matched\n" if !$found;
}
}
}
}
What I can't understand from either your description OR your code is what you intend to happen here.
As it's written, $found gets set to 0 only in the middle foreach loop, so if it's ever set to 1 in the inner loop, it'll remain 1 for all the rest of the inner loop iterations. Is that what you want?
Try to explain clearly what you want this loop to do, both to yourself and to us. Odds are that explaining it to yourself will be enough for you to figure out a better way to code it, but if it isn't, we're here to help...