How could I write a Perl script to calculate the MD5 sum of every file in a directory? [closed]
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/perluse 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.
Use opendir
and readdir
or other recursive method
. Here is an example:
#!/usr/bin/perl -wuse warnings;my $DIR_PATH="a";opendir DIR, ${DIR_PATH} or die "Can not open \"$DIR_PATH\"\n";@filelist = readdir DIR;foreach $file (@filelist) { open(IN,"a/$file")or die "cannot open"; while(<IN>){...} close IN;}