tags:

views:

633

answers:

6

I have a wav file and I need to calculate the MD5 hash of its contents. How can i do that using Perl?

+8  A: 

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).

JB
+2  A: 

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.

wazoox
+7  A: 

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);
Xetius
Far better to slurp using File::Slurp:
Sinan Ünür
Or 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;
hexten
+2  A: 

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";
Sinan Ünür
+6  A: 

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 );
depesz
A: 

You could also use a language agnostic API such as http://www.filemd5.net/API which might solve your problems

JohnnieWalker