尝试在Perl中传递一个子目录作为参数
我有一个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;
}
在它说documentation of File::Find:
您是CHDIR()更改到$文件::查找::迪尔当函数被调用时, 除非指定no_chdir。请注意,在更改目录 时,由于$ File :: Find :: dir,'/'和$ _的并置不是 字面上等于$ File,因此根目录(/)是一个有点特殊的情况 ::查找::名。
所以你其实已经在~/sub
了。只能使用文件名,即$_
。你不需要覆盖它。删除行:
$_ = $File::Find::name;
find
自动更改目录,这样$File::Find::name
不再是相对于当前目录。
您可以删除此行以得到它的工作:
$_ = $File::Find::name;
参见File::Findno_chdir
。
谢谢,删除工作完美。 – com 2013-05-14 04:54:27
从File::Find文档:
对于每一个文件或目录中找到,它会调用&想子程序。 (有关如何使用&想要的功能的详细信息,请参阅以下内容)。 此外,对于找到的每个目录,它将chdir()放入该 目录并继续搜索,调用想要的功能 目录中的每个文件或子目录。
(重点煤矿)
它没有找到./sub/file1.html
的原因是,当open
被调用,文件::查找早已chdir
ED你进入./sub/
。您应该能够打开文件,只需file1.html
。
谢谢,删除完美的工作。 – com 2013-05-14 04:54:06