views:

208

answers:

3

The hash method on a Ruby String returns a number based on the string's length and content:

>> "foo".hash
=> 876516207

What's the equivalent in Perl?

+6  A: 

If you want to get a digest of an arbitrary string, check out the Digest module on CPAN, which supports MD5 and SHA1/2. You can truncate the result for however many characters you need.

friedo
No need to hit CPAN. `Digest` and `Digest::MD5` are core in Perl 5.8, `Digest::SHA` is also core as of Perl 5.10.
daotoad
+3  A: 

Just out of curiosity, what are you going to use the hash for? The Digest module is probably good enough for most purposes, but there are some cases when you might want to roll your own. Rare, but possible.

Sam Post
+3  A: 

You could also take a look at the Ruby source code to see how the hash is generated for String objects in case you want to write something similar in Perl. The resulting hash is a function of the string length and contents and is calculated in rb_str_hash().

muteW