http://qs321.pair.com?node_id=225333

spurperl has asked for the wisdom of the Perl Monks concerning the following question:

Dear monks,

I'm looking for suggestions to optimize the following task:
Given two words, find how many characters they share. For instance, "help" and "temp" share 2 characters, "monk" and "perl" share 0, etc...
First, I implemented the following simple version:
sub score { my ($word1, $word2) = @_; # return a special value (defined somewhere in the file # if we have an exact match) return $words_equal if ($word1 eq $word2); my @chars1 = split(//, $word1); my @chars2 = split(//, $word2); my $count = 0; foreach $a (@chars1) { foreach $b (@chars2) { if ($a eq $b) { $count++; last; } } } return $count; }
Then, I tried optimizing it. The following is a regexp version:
sub score2 { my ($word1, $word2) = @_; return $words_equal if ($word1 eq $word2); my @chars1 = split(//, $word1); my $count = 0; foreach $a (@chars1) { if ($word2 =~ /$a/) { $count++; last; } } return $count; }
Benchmarking proved that the second version is about 50% slower than the first & simple one.

Any ideas on how this can be made faster ?

TIA, Spurperl