http://www.perlmonks.org?node_id=500263


in reply to Hamming Distance Between 2 Strings - Fast(est) Way?

Depending upon your data, simply checking first that the strings don't match can make it much faster :

sub hd1 { #String length is assumed to be equal my ($k,$l) = @_; # next line added return 0 if $k eq $l; my $len = length ($k); my $num_mismatch = 0; for (my $i=0; $i<$len; $i++) { ++$num_mismatch if substr($k, $i, 1) ne substr($l, $i, 1); } return $num_mismatch; }