If $s1 is equal with $s2, the merged region is $s1.

Your 2nd example follows this spec but your 3rd example doesn't. Either your spec and your 2nd example are wrong or your 3rd example is. I think that's the real source of the ambiguity everyone has been pointing out to you. If I had to guess, I'd say your 3rd example is wrong.

Assuming that's the case, I think the following will work:

sub merge { my ($s1, $s2) = @_; my $pos = length($s1) <= length($s2) ? 0 : length($s1) - length($s +2); $pos++ while substr($s1, $pos) ne substr($s2, 0, length($s1) - $po +s); substr($s1,$pos) = $s2; return $s1; }
It assumes that, in the event there is no overlap, the merged string is the concatenation of the two strings. (E.g. merge("ACTG","TCAG") eq "ACTGTCAG") It also assumes that the second string will never be contained in the first unless it is a tail substring. (E.g. merge("GATC", "AT") is "GATCAT" and not "GATC"   but   merge("GATC", "TC) is "GATC".)

Here's how it handles your examples:

$ merge.pl ATTTA TTTAA ATTTAA $ merge.pl ATGTA ATGTA ATGTA $ merge.pl ATGATG ATGATG ATGATG
Note in particular how it handles the your third example as it is different than the answer you provided.

-sauoq
"My two cents aren't worth a dime.";

In reply to Re: Merging Two Strings by sauoq
in thread Merging Two Strings by monkfan

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.