【发布时间】:2013-05-07 18:57:57
【问题描述】:
我有一个 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 概念: 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;
}
【问题讨论】:
标签: perl