This function prints the difference between two strings with Perl:
sub printStringDiff{ my ($s1, $s2) = @_; my @s1 = split(//, $s1); my @s2 = split(//, $s2); while (@s1) { if (defined $s1[0] and defined $s2[0]) { if($s1[0] eq $s2[0]){ print shift @s1; }else{ print color("red"),shift @s1, color("reset"); } }elsif(defined $s1[0]){ print color("red"),shift @s1, color("reset"); } shift @s2; } print "\n"; @s1 = split(//, $s1); @s2 = split(//, $s2); while (@s2) { if (defined $s2[0] and defined $s1[0]) { if($s2[0] eq $s1[0]){ print shift @s2; }else{ print color("red"),shift @s2, color("reset"); } }elsif(defined $s2[0]){ print color("red"),shift @s2, color("reset"); } shift @s1; } print "\n"; }
You need the Module Term::ANSIColor, to highlight the changes,use it like this:
#!/usr/bin/perl use strict; use Term::ANSIColor; printStringDiff("1234","123456"); print "\n"; printStringDiff("123456","1234"); print "\n"; printStringDiff("ABAA","AABA"); print "\n";
And the Result is :