How could I write a Perl script to calculate the MD5 sum of every file in a directory?

user2756257 picture user2756257 · Oct 19, 2013 · Viewed 7.1k times · Source

Is there any way to write a Perl script to calculate the MD5sum of every file in a directory?

If so, how could I do this?

Answer

MattSizzle picture MattSizzle · Oct 19, 2013

Well there are many ways to do this but it comes down to two operations you need to preform. You will first need to locate a list of the files you would like to run the check and then you will need to run the md5sum check on each of those files. There is a ton of ways to do this but the following should work for your needs.

#!/usr/bin/perl

use strict;
use warnings;
use Digest::MD5 qw(md5_hex);

my $dirname = "/home/mgreen/testing/";
opendir( DIR, $dirname );
my @files = sort ( grep { !/^\.|\.\.}$/ } readdir(DIR) );
closedir(DIR);

print "@files\n";

foreach my $file (@files) {
    if ( -d $file || !-r $file ) { next; }
    open( my $FILE, $file );
    binmode($FILE);
    print Digest::MD5->new->addfile($FILE)->hexdigest, " $file\n";
    close($FILE);
}

The above will grab the md5sum for each file in the directory and skip any sub-directories and print it to STDOUT. The MD5 checksum part is then done by the Digest::MD5 module which is ultimately what I think you are looking for.

I do like your question though as it is open-ended with alot of possible solutions like all "How do I do this in perl?" questions so I am sure you will get alot of possible solutions and I will most likely update mine when I get home later.