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.

3
  • 2
    Are you looking for any hashing function or one that specifically gives the same results as Python's (at least for primitive values) Commented Apr 15, 2015 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). Commented Apr 15, 2015 at 15:40
  • sub hash { return unpack("%32W*", "@_") } as the python function makes sense only for the strings? stackoverflow.com/a/793835/223226 Commented Apr 15, 2015 at 16:54

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That will hash a string of bytes. That may or may not be what the needs.
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 !).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.