Question

I am reading the files of a directory into an array. From there, I want to calculate the md5sum of each file from the array and store the fingerprint with filename into another array. For some reason, with the following code, my script seems to keep overwriting the same index in my 2nd array (@md5) instead of storing each md5sum into a seperate index. What is the problem with my code? Output at the bottom of this post.

#!/usr/bin/perl -w

@files = <*>;

foreach $file (@files) {
print $file . "\n";
}

foreach $file (@files) {
@md5 = `md5sum $file`;
$x++;
}

foreach $entry (@md5) {
print $entry . "\n";
}

OUTPUT

./mymd5.pl

ddiff.pl
mymd5.pl
mymd5.pl.save
mymd5.pl.save.1
plgrep.pl
d41d8cd98f00b204e9800998ecf8427e  plgrep.pl
Was it helpful?

Solution

Push your md5 sum onto the array in same order as your file array,

#!/usr/bin/perl -w
use strict;
 @files = <*>;
foreach $file (@files) {
print $file . "\n";
}
foreach $file (@files) {
push(@md5,`md5sum $file`); #md5[n] has sum for file[n]
}
foreach $entry (@md5) {
print $entry . "\n";
}

OTHER TIPS

In the 2nd loop you're overwriting the array with the line(s) output by the most recent md5sum.

2 possible solutions come to mind:

Push the new line(s) onto the end of the array: push(@md5, qx"md5sum $file"); or Store each new array of lines in a containng hash or array: @md5{$file} = qx"md5sum $file" );

I'm thinkin' you're trying for the 1st.

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