【发布时间】:2018-10-16 09:44:38
【问题描述】:
我编写了一个例程来读取两个文件夹及其所有子文件夹中包含的文件的所有名称和大小。根文件夹名称在命令行参数中提供,每个文件夹都在 for 循环中处理,详细信息将输出到两个文件夹中的每一个的单独文件中。但我发现只有两个根文件夹中文件的文件名/大小被输出,我无法更改到子文件夹并重复该过程,因此子目录中的文件被忽略。调试跟踪显示 chdir 命令从未执行,因此我的评估有问题,但我看不到它是什么。 代码是这样的
#!/usr/bin/perl
#!/usr/local/bin/perl
use strict;
use warnings;
my $dir = $ARGV[0];
opendir(DIR, $dir) or die "Could not open directory '$dir' $!";
my @subdirs = readdir(DIR) or die "Unable to read directory '$dir': $!";
for (my $loopcount = 1; $loopcount < 3; $loopcount = $loopcount + 1) {
my $filename = 'FileSize_'.$dir.'.txt';
open (my $fh, '>', $filename) or die "Could not open file '$filename' $!";
for my $subdir (sort @subdirs) {
unless (-d $subdir) {
# Ignore Sub-Directories in this inner loop
# only process files
# print the file name and file size to the output file
print "Processing files\n";
my $size = -s "$dir/$subdir";
print $fh "$subdir"," ","$size\n";
}
elsif (-s "$dir/$subdir") {
# We are here because the entry is a sub-folder and not a file
# if this sub-folder is non-zero size, i.e has files then
# change to this directory and repeat the outer for loop
chdir $subdir;
print "Changing to directory $subdir\n";
print "Processing Files in $subdir\n";
};
}
# We have now processed all the files in First Folder and all it's subdirecorries
# Now assign the second root directory to the $dir variable and repeat the loop
print "Start For Next Directory\n";
$dir = $ARGV[1];
opendir(DIR, $dir) or die "Could not open directory '$dir' $!";
@subdirs = readdir(DIR) or die "Unable to read directory '$dir': $!";;
}
exit 0;
命令行调用是“perl FileComp.pl DiskImage DiskImage1” 但只输出根 DiskImage 和 DiskImage1 文件夹中文件的文件名和文件大小,忽略子文件夹中的所有文件。 永远不会满足更改为“elseif”条件的代码并且永远不会执行代码,因此那里存在错误。 提前感谢您的任何建议。
【问题讨论】:
-
File::Find 对此非常有用。
标签: perl