I have a wav file and I need to calculate the MD5 hash of its contents. How can i do that using Perl?
7 Answers
There is module for it: Digest::MD5::File. With it the code is simplified to:
use Digest::MD5::File qw( file_md5_hex );
my $md5 = file_md5_hex( $some_file_name );
-
link is dead and code does not run (at least for me on default win64 build of active state perl)– KipCommented Jan 27, 2015 at 4:31
Sure you can. Just look for Digest::MD5 for the hashing part, and any WAV-related module if you want to hash a specific part of the file (skipping metadata, for example).
Using the Digest::MD5
use Digest::MD5 qw(md5);
my $hash;
{
local $/ = undef;
open FILE, "$wav_file_name";
binmode FILE;
my $data = <FILE>;
close FILE;
$hash = md5($data);
}
or you could use the OO interface:
use Digest::MD5;
open FILE, "$wav_file_name";
my $ctx = Digest::MD5->new;
$ctx->addfile (*FILE);
my $hash = $ctx->digest;
close (FILE);
-
2
-
6Or don't slurp the whole file at all... WAV files can be large and Digest::MD5 will read from a filehandle: open my $fh, '<', $thewav or die "Can't open $thewav: $!\n"; print Digest::MD%->new->add_file($fh)->hexdigest;– hextenCommented Jun 24, 2009 at 14:45
The following, based on a comment by user hexten, is working for me and should perform better than the answers that slurp the file:
use Digest::MD5 qw( md5_hex );
open my $fh, '<', $file;
my $md5 = Digest::MD5->new->addfile($fh)->hexdigest;
close $fh;
The (currently) top-voted answer suggests using Digest::MD5::File, but that does not work for me at least on the latest Windows build of ActiveState Perl, and the link in the answer is now dead.
Simply use Digest::MD5.
Depending upon your needs, Perceptual Hashing may be interesting too, by the way. It allows you to compare files by comparing their hashes (similar contents have similar hashes). However there still isn't any perl implementation AFAIK.
Using File::Slurp with Digest::MD5:
#!/usr/bin/perl
use strict;
use warnings;
use Digest::MD5 qw(md5_hex);
use File::Slurp;
my ($input) = @ARGV;
write_file "$input.md5", md5_hex(scalar read_file $input, binmode => ':raw'), "\n";
Or Digest::file - Perl v5.20.2 in Debian Jessie
# Poor mans "md5sum" command
use Digest::file qw(digest_file_hex);
for (@ARGV) {
print digest_file_hex($_, "MD5"), " $_\n";
}