in reply to Optimizing a string processing sub
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.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
|
|---|