1

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.
0

1 Answer 1

2

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;               
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.