I'm not sure this is any faster for the two-word case. It does seem simpler, though:
use strict;
while (<DATA>) {
chomp;
print "$_: ", compare(split / /, $_), " in common.\n"
}
sub compare {
my ($word1, $word2) = @_;
my $n = length($word2);
$word2 =~ s/$_// foreach split //, $word1;
return $n - length($word2)
}
__DATA__
perl monk
help temp
frood hoopy
bilbo baggins
jibber jaber
aabcc abbbc
It works by cycling through $word1 one character at a time and removing the first occurance of that character from $word2. When finished, $word2 will be shorter by the number of matches with $word1.