-1

Iam trying to match two variables and get the count of characters that are matched.

For ex:

$name1 = 'cat';

$name2 = 'dcat';

result needs to be 3.

Tried this but always prints 1

$count = 0;
$count++ while ($name1 =~ /$name2/g);
print "$count\n";
Nagaraju
  • 1,853
  • 2
  • 27
  • 46
  • Is order important? ie. is the result with `cat` the same than with `tac`? – Toto Apr 11 '15 at 09:44
  • yes order is important – Nagaraju Apr 11 '15 at 10:19
  • So, must the result with `cat` be the same than with tac? Please update your question to take this into account, add some sample strings an expected result. – Toto Apr 11 '15 at 11:17
  • 2
    Are you asking for the length of the [Longest Common Substring](https://en.wikipedia.org/wiki/Longest_common_substring_problem) – ikegami Apr 11 '15 at 15:00
  • What is the answer you seek if you have `$name1 = 'tac';` and `$name2 = 'dcat';`? ie, are you looking for the length of the substring or the count of the characters contained? What about multiple character matches? –  Apr 12 '15 at 01:08

1 Answers1

0
$count = 0;
$matchstr = "";
foreach (split(//,$name1)){
    $matchstr .= $_;
    $count++ if $name2 =~ /$matchstr/;
}
print "No of matched characters are: $count \n ";
kguest
  • 3,804
  • 3
  • 29
  • 31
Luminos
  • 311
  • 1
  • 3
  • 12