我遇到以下问题: 我试图遍历所有带有数字名称的子目录文件夹,例如:0/1/2 / ... 并尝试检查这样命名的文件:combine_0_arc combine_1_arc ...其中介于两者之间的数字与该文件所在的子文件夹名称相同,以及我是如何做到的:
#!/usr/bin/perl -w
use strict;
opendir(DIR, "./") or die "Failed to open directory: $!\n";
my @DirName = readdir(DIR) or die "Unable to read current directory: $!\n";
#closedir(DIR);
foreach (@DirName){
chomp;
my $CurrentDir =$_;
next if ($CurrentDir eq ".");
next if ($CurrentDir eq "..");
if($CurrentDir =~ /^\d+$/){
# print "Iteration directory: $CurrentDir\n";
opendir(SUBDIR, $CurrentDir) or die "Unable to read current directory: $CurrentDir\n";
my @SubDirFiles = readdir(SUBDIR);
foreach (@SubDirFiles){
chomp;
# if($_ =~ /combine_0_arc/){next;}
if($_ =~ /combine_\d+_arc$/){
my $UntestedArc = $_;
# print "Current directory: $CurrentDir\n";
# print `pwd`."\n";
# print "Combine_arc_name:$UntestedArc\n";
open (FH, "<", $UntestedArc) or die "Cannot open file $UntestedArc:$!\n";
}
}
}
我似乎收到以下错误消息: 无法打开文件combine_0_arc:没有这样的文件或目录
我尝试打印出每次迭代的文件夹名称和文件名,看起来它正确打印出来。我试图为每个文件名或文件夹名称选择那些尾随空格或回车符,但它似乎无法正常工作。谁能解释一下我在那里发生了什么?非常感谢!
答案 0 :(得分:2)
readir返回裸文件名,没有路径。所以加上
foreach my $CurrentDir (@DirName) {
# ...
opendir my $SUBDIR, $CurrentDir;
my @SubDirFiles = map { "$CurrentDir/$_" } readdir($SUBDIR);
foreach my $untestedArc (@SubDirFiles)
{
if ($UntestedArc =~ /combine_${CurrentDir}_arc$/) {
# ...
}
}
}
正则表达式使用 目录的名称,而不是任何数字。
注释
readdir
没有添加新行,不需要chomp
(虽然它没有受到伤害)
使用词法文件句柄
在foreach
语句中声明循环变量(topicalizer)
此答案假定您当前的工作目录是具有@DirName
子目录的目录。
答案 1 :(得分:1)
readdir
只返回目录中的文件名,即相对于匹配opendir
的目录的名称。但是,open
所需要的是文件的绝对名称或相对于您当前所在目录的名称(当前工作目录)。由于opendir
没有神奇地更改工作目录(可以使用chdir
完成),因此工作目录与使用opendir
扫描的目录不同,因此您使用的相对文件也是如此在当前工作目录中找不到open
。