in reply to diff (different enough)

Edit:Sorry, I should have read the answers at the top first. This post doesn't tell anything new.

The following one-line function counts the number of differences in two strings of equal length really quickly:

sub cdiff {my($a,$b,$c)=@_;($c=$a^$b)=~tr/\0//c;}

For strings of different length it produces the correct result unless the longer string contains "\0" characters. I am sure you can add the length comparison if you care about this possibility.

How does it work?

First of all, read the sections in perlman:perlop about the ^ and the tr/// operators (you can search the long page for "XORed" and "stars" and find the right lines).

Now, you understand that $c=$a^$b XORs the two strings as long bit sequences: A bit in $c is 0 when the corresponding bits in $a and $b are equal. Otherwise, the bit is 1.

A byte in $c has eight zeros (that is "\0") when the corresponding bytes in $a and $b are equal. Otherwise, the byte is something else.

We just need to count the bytes in $c that are not "\0". The tr/\0//c operator does just this.

Now, this operator really wants to change the string where it counts (it even thinks that this is his purpose). So, we need a dummy variable $c that can be changed.

That's it.