addfile#

Read an open file handle to EOF and feed every byte into the context.

Synopsis#

open(my $fh, '<:raw', $path) or die $!;
$ctx->addfile($fh);

What you get back#

The same context object, for chaining. addfile reads the handle in 4 KiB blocks and feeds them into MD5 without loading the whole file into memory, so it handles files of any size. Once the call returns, the handle is positioned at EOF; the caller is responsible for closing it.

Put the handle in binmode (or open with :raw) before calling — MD5 hashes bytes, and a text-mode handle on Windows or one with a decoding layer will change what bytes reach the digest.

Examples#

Digest a file in one chain:

open(my $fh, '<:raw', "/etc/passwd") or die $!;
print Digest::MD5->new->addfile($fh)->hexdigest, "\n";
close $fh;

Combine file contents with extra data:

my $ctx = Digest::MD5->new;
$ctx->add($salt);
$ctx->addfile($fh);
$ctx->add($pepper);
my $hex = $ctx->hexdigest;

Skip the object entirely for the one-file common case:

## Same result, shorter:

my $hex = Digest::MD5->new->addfile($fh)->hexdigest;

Edge cases#

  • Croaks with "No filehandle passed" if the argument is not a file handle (including when it is undef or an unopened glob).

  • Croaks with "Reading from filehandle failed" if read returns an I/O error; the context’s state after such a failure is unspecified — discard or reset it.

  • Reading an empty handle (EOF immediately) is a no-op and returns the context unchanged.

  • Handles decoded as UTF-8 still work, but you are hashing the raw decoded bytes the PerlIO layer returns, which is rarely what you want. Prefer binmode.

Differences from upstream#

Fully compatible with upstream Digest::MD5 2.58.

See also#

  • add — feed in-memory data instead of a file

  • add_bits — bit-oriented input for cross-digest compatibility

  • new — typical predecessor when digesting one file

  • hexdigest — typical successor for a single-file chain