2015-07-05 9 views
-1

我想打開目錄並獲取該目錄中的所有文件名而不是子目錄。請幫我在此代碼readdir()試圖在無效的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

回答

2

如果您正確縮進了代碼,則錯誤會很明顯。 closedir在你的循環中!