if $word == $key2 {$UnNum{$key}++);
this adds 1 to $unNum {key} for every instance. What is the value of $key? also $keys2 is a changing variable due to the foreach. So it will rewrite any change you have made for it. Also $keys is a variable so it wouldnt pull the keys out of %UnNum.
foreach my $key2 (keys %UnNum{
foreach my $word(@midwords){
$UnNum{$keys2}++ if ($keys2 eq $word);
}
}
This might be what you mean