Reputation: 35321
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.
Upvotes: 3
Views: 1529
Reputation: 783
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 !).
Upvotes: 1
Reputation: 53498
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.
Upvotes: 1