Digest

The Digest modules (Digest::MD2, Digest::MD5, Digest::SHA1, and Digest::-HMAC) calculate a digest of data that they encounter. These digests are often referred to as “fingerprints,” “hashes,” or “sums.” The Digest modules return a small, fixed-length string, depending on how you’ve requested your data. If you change your data and regenerate the digest, the digest will be different each time the data itself changes. As of Perl 5.8, the Digest modules are bundled with the Perl source kit.

The Digest modules both a functional interface and an object-oriented interface. If you use the object-oriented inteface, you have the benefit of being able to send data of arbitrary length. You can also tell the Digest module to read files directly.

Digest delivers the hashed data in one of three formats: binary, hex, or base64. The following example uses Digest and calculates an MD5 sum of a string, $text, that represents the data. The data is output in hexadecimal form.

#!/usr/local/bin/perl -w
use Digest;
my $text = 'Be the ball, Danny!';
my $md5 = Digest->MD5;

$md5->add($text);
my $hashed = $md5->hexdigest;

print "The sum of \$text is [$hashed].\n";

This gives you:

The sum of $text is [6eec91414372ad157fc9d3d15b496d93].

Digest implements the following functions for the object-oriented interface. These functions are available to all of the Digest modules.

Get Perl in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.