Perl无法找到并打开现有的文件名,即使我可以打印出完全相同的文件名
我有如下类似的问题: 我试图遍历所有具有数字名称的子目录文件夹,例如:0/1/2/。。。 并尝试检查名为以下内容的文件:combine_0_arc combine_1_arc。。。其中,中间的数字与此文件存在的子文件夹名称相同,我是这样做的:Perl无法找到并打开现有的文件名,即使我可以打印出完全相同的文件名,perl,Perl,我有如下类似的问题: 我试图遍历所有具有数字名称的子目录文件夹,例如: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 "U
#!/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";
}
}
}
#/usr/bin/perl-w
严格使用;
opendir(DIR,“./”)或die“无法打开目录:$!\n”;
my@DirName=readdir(DIR)或die“无法读取当前目录:$!\n”;
#closedir(DIR);
foreach(@DirName){
咀嚼;
my$CurrentDir=$\;
下一个if($CurrentDir eq“);
下一个if($CurrentDir eq.“);
如果($CurrentDir=~/^\d+$/){
#打印“迭代目录:$CurrentDir\n”;
opendir(SUBDIR,$CurrentDir)或die“无法读取当前目录:$CurrentDir\n”;
my@SubDirFiles=readdir(SUBDIR);
foreach(@SubDirFiles){
咀嚼;
#如果($\u=~/combine\u 0\u arc/){next;}
如果($\ux=~/combine\ud+\u arc$/){
我的$UntestedArc=$\;
#打印“当前目录:$CurrentDir\n”;
#打印“pwd”。“\n”;
#打印“合并弧名称:$UntestedArc\n”;
open(FH),readdir
只返回目录中的文件名,即与匹配的opendir
中给定的目录相关的名称。但是,open
需要的是文件的绝对名称或与当前所在目录(当前工作目录)相关的名称。因为opendir
不会神奇地更改工作目录(这可以通过chdir
完成)工作目录与使用opendir
扫描的目录不同,因此在当前工作目录中找不到您在open
中使用的相关文件。返回裸文件名,没有路径。因此添加它
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
子目录的目录。请忽略末尾缺少的最后一个括号。当我在此处复制代码时,看起来我缺少了一个括号。我调用脚本的目录级别是包含所有子目录的根目录:0/1/2/…非常感谢。你的解决方案很好。我以前尝试调用系统命令更改到当前目录,但失败了。你们帮了大忙。谢谢。更改目录确实是另一种方式。在@DirName
的循环中,你说my$old=cwd;chdir$CurrentDir;
。(需要为Cwd
使用Cwd;
),然后readdir
的输出(没有路径的文件名)是您当前工作目录中的文件名,因此您不必预先指定目录名。但是,您必须在循环结束时将目录更改回,chdir$old;
所有这些都假定您当前的工作目录是具有@DirName
子目录的目录@王云龙 我更正了我以前的评论,一段代码是错误的。(chdir
在更改它之前不会返回当前工作目录。)只是让你知道,以防你打算使用它。谢谢,伙计,我忘了有“chdir”“功能。我以前尝试过cd$DestinationFolder
,但这种方式似乎不起作用。这解决了我的疑问。非常感谢