我得到了以下功能,并且不知道如何将输出放入变量。
sub checkFiles {
# Declaration
my $origDir="/home/hbo/test/chksum/";
my $tmpDir="/home/hbo/test/tmp/";
# get directory inventory
opendir( DIR, $origDir);
my @files = sort ( grep { !/^\.|\.\.}$/ } readdir(DIR) );
closedir(DIR);
foreach my $file (@files) {
if ( !-r $origDir.$file) { print $origDir.$file, "does not exist"; next;}
# open filehandles
open my $a_fh, '<', $origDir.$file or die "$origDir.$file: $!";
open my $b_fh, '<', $tmpDir.$file or die "$tmpDir.$file: $!";
# map difference
my %tmpDirFile;
@tmpDirFile{map { unpack 'A*', $_ } <$b_fh>} = ();
# print difference
while (<$a_fh>) {
print unless exists $tmpDirFile{unpack 'A*', $_};
}
close $a_fh;
close $b_fh;
}
}
我得到的问题是&#34;打印除非存在$ tmpDirFile {unpack&#39; A *&#39;,$ _};&#34;我想把这个输出放到一个像数组的变量中,我可以决定&#34;更改&#34;或&#34;删除&#34;或&#34;新&#34;。我的脚本将做的简短摘要:它构建目录的md5总和,检查目录是否与之前的版本不同,并使用#34; new&#34;,&#34;删除&#34等标志打印差异;,&#34;改变了#34;。是的,我不想使用其他库。
控制台上的输出是:
40567504a8a2f9f665695a49035b381b /home/hbo/test/somedir/some/some.conf
现在我想显示文件是否已更改,已删除或是否为新文件。因此我需要将输出放入变量中。有人能帮助我吗?
答案 0 :(得分:0)
您可以使用哈希来做到这一点。它有点像计数,只是你不是简单地计算,而是保留每个键中的文件列表。它看起来像这样:
{
new => [
'file1',
'file3',
],
deleted => [
'file4',
],
changed => ]
'file5',
],
},
在循环外创建该哈希(或在我的示例中为哈希引用),然后在适当的密钥中推入数组ref。您甚至不需要创建数组引用, autovivification 将为您处理。
my $diff; # we keep track here
foreach my $file (@files) {
# ...
while (my $line = <$a_fh>) {
if ( exists $tmpDirFile{unpack 'A*', $line} ) {
# do stuff to check what the difference is
if ( find_diff($line) ){
push @{ $diff->{changed} }, $line;
} else {
push @{ $diff->{deleted} }, $line;
}
} else {
push @{ $diff->{new} }, $line;
}
}
}