Question

i have spent the last 3 days trying to figure out why i cannot get an single file in a directory to show. i can get md5 of any single file, but not if its in a directory.

this script will list the files, but it will not list the md5 of any of the files in the directory.

here is the code i am working with:

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

my $dirname = "./directory_name";
opendir( DIR, $dirname );
my @files = readdir(DIR);
closedir(DIR);

print "@files\n";

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

its a simple script to get md5's of each file in a directory and is very useful for me

Was it helpful?

Solution

Always check your error status $! of open or include use autodie at the top of your script. You're calling open but assuming it works. Because you're missing path information for the files, it's likely that they aren't being found and are all being skipped by the -r check.

One solution for getting the path info included is to just use a file glob instead of readdir

use strict;
use warnings;
use autodie;

use Digest::MD5;

my $dirname = "./directory_name";

foreach my $file (<$dirname/*>) {
    next if -d $file;
    open( my $FILE, '<:raw', $file );
    print Digest::MD5->new->addfile($FILE)->hexdigest, " $file\n";
}

Additionally, be sure to open your files in :raw or binmode or they may return incorrect values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top