in reply to looping foreach error

You declare "$sequence" outside of the foreach loop so if there are no matches within a loop it will print out the match from the previous loop. Try resetting $sequence at the start of the loop:
foreach my $match(@exonic_matches) { $sequence = ''; # ...