我有一个Perl程序来读取.html,只有当程序与.html文件位于同一目录时才有效。
我希望能够在不同的目录中开始并将html的位置作为参数传递。该程序(下面的shell例子)遍历子目录“sub” 及其子目录以查找.html,但只在我的perl文件位于同一子目录“sub”时有效。如果我将Perl文件 放在主目录中,这是从子目录“sub”退一步,它不起作用。尝试在Perl中传递一个子目录作为参数
在shell中,如果从我的主目录键入“perl project.pl ./sub”,则说明 未打开./sub/file1.html。无此文件或目录。然而,该文件确实存在于该确切位置。 file1.html是它正在尝试读取的第一个文件。
如果我将shell中的目录更改为该子目录,并将.pl文件 移到那里,然后在shell中声明:“perl project.pl ./”,一切正常。
要使用文件搜索的目录,我一直::查找的概念,我发现这里: How to traverse all the files in a directory; if it has subdirectories, I want to traverse files in subdirectories too Find::File to search a directory of a list of files
#!/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;
}
谢谢,删除完美的工作。 – com 2013-05-14 04:54:06