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

Hello monks!
I have a question:
Say you have the strings:
$a="ABCDABCDXBCDABCXABCDXXCDABXD"; $b="ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD";

If in $a there were no X's, then with a pattern match you would say that $b includes $a. I need to write a pattern match to "ignore" other characters in $a if they are X, but DO NOT erase them. What I mean is that, in the position of X in $a, you could have A, B, C or D, does not matter. I tried the following but did not work:
$a="ABCDABCDXBCDABCXABCDXXCDABXD"; $b="ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD"; @split_initial=split(//, $a); for ($i=0; $i<=$#split_initial; $i++) { if($split_initial[$i] ne 'A' && $split_initial[$i] ne 'B' && $spli +t_initial[$i] ne 'C' && $split_initial[$i] ne 'D') { $split_initial[$i]="*"; } $seq_final=join('', @split_initial); } if ($b=~/$seq_final/) {print "OK\n";}

I somehow try to insert artificially, the wildcharacter * in $a, so as to "ignore" what's in position of X (because it can be anything between A,B,C or D -it doesn't matter which one) when it searches $b for the presence of $a..
How can I write this pattern match correctly?

Replies are listed 'Best First'.
Re: pattern matching with substring containing special character
by GrandFather (Saint) on Mar 03, 2011 at 01:18 UTC

    Replace the Xs with a character class match [ABCD] then use the resulting string as the match string:

    use strict; use warnings; my $match = "ABCDABCDXBCDABCXABCDXXCDABXD"; my $str = "ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD"; $match =~ s/x/[abcd]/ig; print "Matched $1\n" if $str =~ /($match)/i;

    Prints:

    Matched ABCDABCDABCDABCDABCDABCDABCD
    True laziness is hard work
      Oh yes, great, I accidentally wrote "*" instead of "." as you pointed out... GrandFather, thanks also for your recommendation, good to learning new tricks!
Re: pattern matching with substring containing special character
by roboticus (Chancellor) on Mar 03, 2011 at 01:15 UTC

    Try using a regex, by replacing your 'X' with '.', you can easily check if they match, something like (untested):

    my $t="ABCDABCDXBCDABCXABCDXXCDABXD"; $t =~ s/X/./g; my $u="ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD"; if ($u =~/$t/) { print "match found\n"; }

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.