perl - 使用 PERL 获取子目录中所有文件的名称和大小
问题描述
我编写了一个例程来读取两个文件夹及其所有子文件夹中包含的文件的所有名称和大小。根文件夹名称在命令行参数中提供,每个文件夹都在 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”条件的代码并且永远不会执行代码,因此那里存在错误。提前感谢您的任何建议。
解决方案
该检查很可能总是错误的,因为您正在查看错误的内容。
unless (-d $subdir) {
$subdir
是内部文件或目录的文件名,$dir
因此要访问它,您需要使用完整的相对路径,$dir/$subdir
就像您在这里所做的那样:
my $size = -s "$dir/$subdir";
如果您确实修复了该unless
检查,您也会遇到问题,因为这样做chdir
也会导致问题,因为您在阅读$dir
内容的过程中正在这样做,因此将在错误的位置查看$dir/$subdir
.
推荐阅读
- function - 检查 2 个文件位置中的文件的功能不起作用
- javascript - 粒子 JS 的问题
- python - boto3 s3 api 在调用 GetBucketPolicyStatus 操作时失败并显示“(NoSuchBucketPolicy)”
- c# - 新插入的记录是否可用于同一事务中的后续 SQL 命令?
- autodesk-forge - 文件夹权限批量更新端点返回“访问被拒绝”错误
- c - 尝试扫描并打印结构中的字符串
- java - Swagger-Core 的对立面?
- spring-boot - 为什么我的 Spring Boot 单元测试不会在服务类中加载 @Value 属性?
- python - Python - 带有 STDIN 和 STDOUT 的子进程
- pine-script - 如何使用 Pine 脚本在监视列表中选择符号