This function prints the difference between two strings with Perl:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
#!/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 :