Just another try:
use strict; my $a = "This is a sentence"; my $b = "This is another sentecne"; my @matches = match_words($a,$b); print join(" ",@matches),"\n"; print scalar(@matches); sub match_words{ my @word_list1 = split(/\s+/,$_[0]); my @word_list2 = split(/\s+/,$_[1]); my $i = 0; while(defined($word_list1[$i]) && defined ($word_list2[$i]) && $word_list1[$i] eq $word_list2[$i]){ ++$i; } return splice @word_list1, 0, $i; } __END__ This is 2
updated: You need to use the match_words() in array context, if you use it in scalar context, it will return the last one matched (e.g., "is" in this example), this is due to the same behavior for splice. To solve this problem, you may want to replace the return statment in the sub by
my @result = splice @word_list1,0,$i; return @result;

In reply to Re: Number of matching words by johnnywang
in thread Number of matching words by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.