我有一个 Perl 程序来读取 .html 文件,并且仅当程序与 .html 文件位于同一目录时才有效。
我希望能够从不同的目录开始并将 html 的位置作为参数传递。该程序(下面的shell示例)遍历子目录“sub”及其子目录以查找.html,但仅当我的perl文件位于同一子目录“sub”中时才有效。如果我将 Perl 文件放在主目录中,即从子目录“sub”退后一步,它就不起作用。
在 shell 中,如果我从我的主目录中键入“perl project.pl ./sub”,它会显示无法打开 ./sub/file1.html。没有相应的文件和目录。然而,该文件确实存在于那个确切的位置。file1.html 是它尝试读取的第一个文件。
如果我将 shell 中的目录更改为该子目录并将 .pl 文件移动到那里,然后在 shell 中说:“perl project.pl ./”一切正常。
为了搜索目录,我一直在使用我在这里找到的 File::Find 概念: 如何遍历目录中的所有文件;如果它有子目录,我也想遍历子目录中的文件 Find::File 来搜索文件列表的目录
#!/usr/bin/perl -w
use strict;
use warnings;
use File::Find;
find( \&directories, $ARGV[0]);
sub directories {
$_ = $File::Find::name;
if(/.*\.html$/){#only read file on local drive if it is an .html
my $file = $_;
open my $info, $file or die "Could not open $file: $!";
while(my $line = <$info>) {
#perform operations on file
}
close $info;
}
return;
}