daffodil
daffodil

Reputation: 197

List file in directory and store in array. That array can be access outside the loop

I want to list the files in the folder and want to store in array. How can I make the array can be access outside the loop? I need that array to be outside as need to use it outside the array

This is the code:

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;

The error message is

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

Upvotes: 1

Views: 51

Answers (1)

ggorlen
ggorlen

Reputation: 56895

You're pushing the unitialized variable $_ onto the array rather than $filelist, which is misleadingly named (it's just one file name).

You can use:

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;               

Upvotes: 2

Related Questions