readdir() 尝试无效的 dirhandle DIR

readdir() attempted on invalid dirhandle DIR

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

#!/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

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