Seems that John's regex approaches are (much) faster:
Rate HD_string HD_jkrahn2 HD_jkrahn1 HD_string 203251/s -- -18% -76% HD_jkrahn2 247033/s 22% -- -71% HD_jkrahn1 848840/s 318% 244% --
__BEGIN__ #!/usr/bin/perl -w use Benchmark 'cmpthese';
my $a = 'AAAA'; my $b = 'AAAB';
print hamming_distance_string($a,$b),"\n"; print hamming_distance_jkrahn1($a,$b),"\n"; print hamming_distance_jkrahn2($a,$b),"\n";
cmpthese (-5, {HD_string => "hamming_distance_string($a,$b)", HD_jkrahn1 =>"hamming_distance_jkrahn1($a,$b)", HD_jkrahn2 =>"hamming_distance_jkrahn2($a,$b)"});
sub hamming_distance_string { #String length is assumed to be equal my ($a,$b) = @_; my $len = length ($a); my $num_match=0;
for (my $i=0; $i<$len; $i++) { # assume that the lists are of same length
++$num_match if substr($a, $i, 1) eq substr($b, $i, 1);
}
#my $weight = $num_match/$len;
return $num_match; }
sub hamming_distance_jkrahn1 { my $ret = ( $_[0] ^ $_[1] ) =~ tr/\0//; $ret }
sub hamming_distance_jkrahn2 { my $ret = () = ( $_[0] ^ $_[1] ) =~ /\0/g; $ret }
__END__
-- Edward WIJAYA Singapore
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>