Daily Archives: March 10, 2008

perl: String hashCode

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.

3 Comments

Filed under perl

GMail Slow

One of the reasons I switched from Yahoo! and Hotmail to GMail is the fact that it supports https not only at the time of login but also during the rest of the session. One advantage with this is, even if you send personal emails from anywhere outside home, no one would know what you are sending/receiving. Gives that extra level of privacy comfort if not anything else. However, last few weeks I have been observing performance problems with GMail. I have been using https for almost a few yrs now that I didn’t bother to try the http version. Today I tried the http version and to my surprise, it is much faster. Hopefully their https servers will continue to work faster, otherwise my incentive to use GMail would reduce given that now a ways all the other major email providers like Yahoo! and Hotmail (would it become Yahmail in the future? :)) also started giving GBs of storage.

Leave a comment

Filed under Gmail