use strict; use warnings; use Digest::MD5; my $sourcedirectory = '//path/to/directory'; &main(); sub main { # creating file array my @files = &getfiles($sourcedirectory); # removal of the two directory structures which form the start of the file array my $rmdir = shift (@files); my $rmdir2 = shift (@files); # capture of a count of the number of files remaining in the array my $filecount = @files; # check to see if there are no files, if none, exit script if ($filecount == 0) { print "\nNo files to process\n\n"; exit; } # where there are files, the routine subroutine is called for each item individually (except for md5 file types) else { foreach my $item (@files) { next if $item =~ /.md5/; my $filepath = "$sourcedirectory/$item"; &routine($filepath, $item); } } } sub routine { # identify filepath and name as parameters passed to routine my $file = shift; my $name = shift; # open file, set to binary mode, close and process MD5 open my $fh, '<', $file or die "Can't open file: $!"; binmode ($fh); my $md5tocompare = &processmd5($fh); close $fh or die "Can't close file successfully: $!"; # check file.md5 existence and open and read to memory open my $fh2, '<', "$file.md5" or next; my $originalmd5 = <$fh2>; close $fh2 or die "Can't close file successfully: $!"; # check parity print "MD5 is $md5tocompare against orignal MD5 of $originalmd5\n"; next if $md5tocompare eq $originalmd5; &logmd5($md5tocompare, $name); } # subroutine to process the MD5 Hex value of a filehandle passed sub processmd5 { my $io_handle = shift; my $md5 = Digest::MD5->new; $md5->addfile($io_handle); my $value = $md5->hexdigest; return $value; } # logreport subroutine that receives a string message as an argument, and processes the log entry sub logmd5 { # message, and definition of date/time variables to enable logging my $md5 = shift; my $md5filename = shift; my $md5file = "$sourcedirectory/Log.txt"; # opening of log and appending of md5 to the log open(LOG, '>>', $md5file) or die "Can't open logfile $!"; print LOG "ERROR: $md5filename does not match - $md5 is not the original checksum"; close LOG; } # a subroutine to enable definition of files to be processed sub getfiles { my $sourcefiles = shift; my @file_list; opendir(DIR, $sourcefiles) or die "Can't open directory, $!\n"; @file_list = readdir(DIR); closedir(DIR); return @file_list; }