Perl print String difference

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 :

ColorStringDiff

Perl Terminal Colours

This example shows how to print some colours with Perl.

print "e[37m whiten";
print "e[33m yellown";
print "e[36m cyann";
print "e[34m bluen";
print "e[32m greenn";
print "e[35m majentan";
print "e[31m redn";
print "e[30m blackn";
print "e[37m back to whiten";

The result looks like this:

Screenshot_Color_Terminal

On some Terminal it don’t work, so another solution is to use the Module Term::ANSIColor:

#!/usr/bin/perl
use strict;
use Term::ANSIColor;

my @color = qw(black red green yellow blue magenta cyan white);

for my $col (@color){
	print color($col),$col, color($col),"\n";
}
print "default\n"

Result is now:

TerminalColor