简体   繁体   English

perl数组不正确地将值分配给索引(保留覆盖相同索引的基)

[英]perl array improperly assigning values to indices (keeps overwriting same index)

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. 从那里,我想从数组中计算每个文件的md5sum,并将带有文件名的指纹存储到另一个数组中。 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. 出于某种原因,使用以下代码,我的脚本似乎继续覆盖第二个数组(@ md5)中的相同索引,而不是将每个md5sum存储到单独的索引中。 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

In the 2nd loop you're overwriting the array with the line(s) output by the most recent md5sum . 在第二个循环中,您将用最新的md5sum输出的行覆盖数组。

2 possible solutions come to mind: 有两种可能的解决方案:

Push the new line(s) onto the end of the array: push(@md5, qx"md5sum $file"); 将新行push(@md5, qx"md5sum $file");数组的末尾: push(@md5, qx"md5sum $file"); or Store each new array of lines in a containng hash or array: @md5{$file} = qx"md5sum $file" ); 或将每个新的行数组存储在containng哈希或数组中: @md5{$file} = qx"md5sum $file" );

I'm thinkin' you're trying for the 1st. 我想您正在尝试第一项。

Push your md5 sum onto the array in same order as your file array, 按与文件数组相同的顺序将md5 sum推入数组,

#!/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";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM