I had a need to create unique numbers out of strings. So, I explored the option of using hashcodes (which won’t be 100% unique especially if they need to be represented in limited number of bits). I couldn’t find any function suitable within perlfunc. After doing a bit of research on the web and not wanting to spend too much time understanding the theory, I just looked at java.lang.String source code and the hashcode function was like
hash = 0;
for(character in string) {
hash = 31*hash+character;
}
So far so good. When I tried this with perl, I got completely different answer. So, it turns out this is because, by default perl doesn’t use integer arithmetic in calculations. But you can force it to do so with “use integer;” and most importantly, this behavior can be controlled by block. So, here is my final perl String hashCode function that is same as Java’s implementation of a String hashCode.
sub hashCode {
my $hash = 0;
use integer;
foreach(split //,shift) {
$hash = 31*$hash+ord($_);
}
return $hash;
}
That’s it.