问题描述
我有一个文件夹,并且其中有很多子文件夹.在那些子文件夹中,我有许多.html文件可供读取.我已经编写了以下代码来做到这一点.它打开父文件夹以及第一个子文件夹,并且仅打印一个.html文件.它显示错误:
I have a folder and inside that I have many subfolders. In those subfolders I have many .html files to be read. I have written the following code to do that. It opens the parent folder and also the first subfolder and it prints only one .html file. It shows error:
NO SUCH FILE OR DIRECTORY
我不想更改整个代码.现有代码中的任何修改对我都是有益的.
I dont want to change the entire code. Any modifications in the existing code will be good for me.
use FileHandle;
opendir PAR_DIR,"D:\\PERL\\perl_programes\\parent_directory";
while (our $sub_folders = readdir(PAR_DIR))
{
next if(-d $sub_folders);
opendir SUB_DIR,"D:\\PERL\\perl_programes\\parent_directory\\$sub_folders";
while(our $file = readdir(SUB_DIR))
{
next if($file !~ m/\.html/i);
print_file_names($file);
}
close(FUNC_MODEL1);
}
close(FUNC_MODEL);
sub print_file_names()
{
my $fh1 = FileHandle->new("D:\\PERL\\perl_programes\\parent_directory\\$file")
or die "ERROR: $!"; #ERROR HERE
print("$file\n");
}
推荐答案
您没有在print_file_names()
函数中提取提供的$file
参数.
You're not extracting the supplied $file
parameter in the print_file_names()
function.
应该是:
sub print_file_names()
{
my $file = shift;
...
}
您的-d
测试在外部循环中看起来也是错误的,顺便说一句.您说的是next if -d ...
,这意味着它将跳过目录的内部循环,这似乎与您的要求完全相反.完全起作用的唯一原因是因为您正在测试$file
,它只是相对于路径的文件名,而不是完整的路径名.
Your -d
test in the outer loop looks wrong too, BTW. You're saying next if -d ...
which means that it'll skip the inner loop for directories, which appears to be the complete opposite of what you require. The only reason it's working at all is because you're testing $file
which is only the filename relative to the path, and not the full path name.
另请注意:
- Windows上的Perl使用
/
作为路径分隔符可以很好地应对 - 设置一次父目录,然后从中导出其他路径
- 使用
opendir($scalar, $path)
代替opendir(DIR, $path)
- Perl on Windows copes fine with
/
as a path separator - Set your parent directory once, and then derive other paths from that
- Use
opendir($scalar, $path)
instead ofopendir(DIR, $path)
nb:未测试的代码如下:
nb: untested code follows:
use strict;
use warnings;
use FileHandle;
my $parent = "D:/PERL/perl_programes/parent_directory";
my ($par_dir, $sub_dir);
opendir($par_dir, $parent);
while (my $sub_folders = readdir($par_dir)) {
next if ($sub_folders =~ /^..?$/); # skip . and ..
my $path = $parent . '/' . $sub_folders;
next unless (-d $path); # skip anything that isn't a directory
opendir($sub_dir, $path);
while (my $file = readdir($sub_dir)) {
next unless $file =~ /\.html?$/i;
my $full_path = $path . '/' . $file;
print_file_names($full_path);
}
closedir($sub_dir);
}
closedir($par_dir);
sub print_file_names()
{
my $file = shift;
my $fh1 = FileHandle->new($file)
or die "ERROR: $!"; #ERROR HERE
print("$file\n");
}
这篇关于如何在Perl中读取多个目录并读取子目录的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!