readdir()尝试了无效的dirhandle DIR

时间:2015-07-05 06:05:54

标签: perl regex-negation

我想打开目录并获取该目录中的所有文件名,而不是子目录。请帮我修正一下这段代码

#!/usr/bin/perl

use strict;
use warnings;
use Getopt::Long;
my $opt_section;
my $opt_content;
my $opt_help = 0;

 &GetOptions (
"help"          => \$opt_help,
"section:s"        => \$opt_section,
"content:s"        => \$opt_content,
);

if ($opt_help) {
print "USAGE: file.pl -section <section> -content <content> \n ";

    exit;}

my $dir ="/home/priya/scripts/test/${opt_section}/${opt_content}/latest";                             #base directory to look up for the files

print"$dir \n";

opendir(DIR, $dir) or die "Unable to read Directory : $!";
while (my $file = readdir(DIR)) {
        #Only files not subdirectories
        next unless (-f "$dir/$file");
        #Use a regular expression to find files ending in .txt
        $file =~ m/^${opt_section}.+txt$/i;
print "$file \n";

closedir(DIR);
}
exit 0;

执行

时出现此错误

它正在读取第一个文件并将其命名为输出,然后给出此错误

readdir()尝试使用无效的dirhandle DIR

1 个答案:

答案 0 :(得分:2)

如果您正确缩进代码,错误就会很明显。 closedir在您的循环中!