Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two strings and highlight mismatch characters in Perl

Tags:

perl

Consider:

string1 = "AAABBBBBCCCCCDDDDD"
string2 = "AEABBBBBCCECCDDDDD"

output. Where the mismatch (in this case E) will be replaced with HTML tags around E that color it.

A**E**ABBBBBCC**E**CCDDDDD

What I tried so far: XOR, diff and substr. First I need to find the indices then replace those indices with the pattern.

like image 554
Jabda Avatar asked May 21 '13 23:05

Jabda


People also ask

How to Compare string in PERL?

“Many options exist in PERL to compare string values. One way is to use the “cmp” operator, and another way is to use comparison operators, which are “eq,” “ne,” “lt.” and “gt.” The “==” operator is used for number comparison only in PERL.

How do I compare two characters in a string?

You can compare two Strings in Java using the compareTo() method, equals() method or == operator. The compareTo() method compares two strings. The comparison is based on the Unicode value of each character in the strings.


2 Answers

my @x = split '', "AAABBBBBCCCCCDDDDD";
my @y = split '', "AEABBBBBCCECCDDDDD";

my $result = join '',
             map { $x[$_] eq $y[$_] ? $y[$_] : "**$y[$_]**" }
             0 .. $#y;
like image 60
FMc Avatar answered Sep 19 '22 20:09

FMc


Use:

use strict;
use warnings;

my $string1 = 'AAABBBBBCCCCCDDDDD';
my $string2 = 'AEABBBBBCCECCDDDDD';
my $result = '';
for(0 .. length($string1)) {
    my $char = substr($string2, $_, 1);
    if($char ne substr($string1, $_, 1)) {
        $result .= "**$char**";
    } else {
        $result .= $char;
    }
}
print $result;

It prints A**E**ABBBBBCC**E**CCDDDDD and was tested somewhat, but it may contain errors.

like image 41
mzedeler Avatar answered Sep 22 '22 20:09

mzedeler