在目录中列出文件并存储在数组中。该数组可以在循环外访问

时间:2019-06-12 01:02:03

标签: perl

我想列出文件夹中的文件,并想存储在数组中。如何使数组可以在循环外部访问?我需要将该数组放置在外部,因为需要在该数组外部使用

这是代码:

use strict;
use warnings;

my $dirname       = "../../../experiment/";
my $filelist;
my @file;

open ( OUTFILE, ">file1.txt" );

opendir ( DIR, $dirname ) || die "Error in opening dir $dirname\n";

while ( $filelist = readdir (DIR) ) {

   next if ( $filelist =~ m/\.svh$/ );
   next if ( $filelist =~ m/\.sv$/ );
   next if ( $filelist =~ m/\.list$/ );

   push @fileInDir, $_; 

}

closedir(DIR);

print OUTFILE " ", @fileInDir;

close OUTFILE;

错误消息是

Use of uninitialized value in print at file.pl line 49.

1 个答案:

答案 0 :(得分:2)

您要将单位化变量$_推到数组上,而不是将$filelist推到数组上,后者被误认为是一个文件名。

您可以使用:

use strict;
use warnings;

my $dirname = "../../../experiment/";
my $fname = "file1.txt";
my @files;

open my $out_fh, ">", $fname or die "Error in opening file $fname: $!";
opendir my $dir, $dirname or die "Error in opening dir $dirname: $!";

while (my $file = readdir($dir)) {
   next if ($file =~ m/\.svh$/);
   next if ($file =~ m/\.sv$/);
   next if ($file =~ m/\.list$/);
   push @files, $file;
}

print $out_fh join "\n", @files;
closedir $dir;
close $out_fh;