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

Dear Monks, I was wondering if anybody would have an elegant solution to replacing letters in one string based on the occurrence of a letter in another. I have two strings str1 = "ABCXXFGH" str2 = "XXCDEFGH" and I would like to output str3 = "XXCXXFGH" Thanks for any pointers, Cheers Iain
  • Comment on Replacing letters in one string based on another

Replies are listed 'Best First'.
Re: Replacing letters in one string based on another
by BrowserUk (Patriarch) on Sep 16, 2010 at 21:57 UTC

    $str1 = "ABCXXFGH"; $str2 = "XXCDEFGH";; tr[X][\x00] for $str1, $str2;; ( $str3 = $str1 & $str2 ) =~ tr[\x00][X];; print $str3;; XXCXXFGH

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Replacing letters in one string based on another
by GrandFather (Saint) on Sep 16, 2010 at 23:08 UTC

    Can you guarantee that all letters in the strings to be merged are the same except where there is an 'X'? If so BrowserUK's solution is what you are looking for. If not then you have a little more work to do and you need to specify what ought happen for mismatched characters.

    True laziness is hard work
Re: Replacing letters in one string based on another
by umasuresh (Hermit) on Sep 16, 2010 at 22:05 UTC
    Try this:
    use strict; use warnings; my $str1 = "ABCXXFGH"; my $str2 = "XXCDEFGH"; my $str3 = "XXCXXFGH"; my ($str_to_retain) = $str2 =~ /(\w\w\w).*/; my ($replacement) = $str1 =~ /\w\w\w(.*)/; my $replaced_str = $str_to_retain.$replacement; print "$str3\n$replaced_str\n";

      But BrowserUk's approach will work for any two strings (Update: assuming, as GrandFather points out, that the two strings are identical except for the Xs), while your solution depends on the particular structure of the strings given in the example of the OP.