3

The summary documentation for Python's hash function reads:

Type:        builtin_function_or_method
String form: <built-in function hash>
Namespace:   Python builtin
Docstring:
hash(object) -> integer

Return a hash value for the object.  Two objects with the same value have
the same hash value.  The reverse is not necessarily true, but likely.

(For example, the hash function when applied to the documentation string above returns the integer 3071661466461282235.)

Is there an equivalent function for Perl?

EDIT: What I'm looking for does not need to return the same value as Python's hash function for any argument.

mpapec
  • 50,217
  • 8
  • 67
  • 127
kjo
  • 33,683
  • 52
  • 148
  • 265
  • 2
    Are you looking for *any* hashing function or one that specifically gives the same results as Python's (at least for primitive values) – Quentin Apr 15 '15 at 15:35
  • @Quentin: thanks for your question; I've added a clarification to my post. In short, agreement with Python's `hash` is not necessary (though, now that you mention it, it would be kind of nice, but only as a pleasant bonus, not at all required). – kjo Apr 15 '15 at 15:40
  • `sub hash { return unpack("%32W*", "@_") }` as the python function makes sense only for the strings? http://stackoverflow.com/a/793835/223226 – mpapec Apr 15 '15 at 16:54

2 Answers2

1

There are a variety of ways of hashing an object. The best way to do this with perl is via a module.

E.g. Digest::SHA

Which would work like this:

use Digest::SHA qw(sha1 sha1_hex sha1_base64 ...);

$digest = sha1($data);
$digest = sha1_hex($data);
$digest = sha1_base64($data);

$digest = sha256($data);
$digest = sha384_hex($data);
$digest = sha512_base64($data);

You can see a list of the various choices by running i /Digest/ in the CPAN shell perl -MCPAN -e shell. Digest::MD5 is another common choice for this.

I would suggest for trivial implementations, it doesn't actually make much difference which you use. If it's non trivial then there are security concerns relating to hash collisions.

Sobrique
  • 52,974
  • 7
  • 60
  • 101
1

First, you should overload "to-string" method of your object. It might be enough if you want just to use objects as keys in hashes. Perl applies some internal hash mechanism for quick key-value access.

Second, you can apply any hashing mechanism to the resulting string, e.g. Digest::SHA, or, if you don't need strong security requirements, then yo can use Digest::MurmurHash (The announced speed for MurmurHash is 5Gb/s !).

Ivan Baidakou
  • 713
  • 9
  • 14