Hi, all, I am a Perl newbie.

I need to read multiple files in a loop and read each file into an array. I wrote the following code, but it doesn't work. Basically my question is how to assign a different array in the loop? Can anybody help? Thanks a lot!

for($x=0;$x<10;$x++){
	open(INPUT, "$Array[$x]") || die "Cannot open : $! \n";
	@contents_$x = <INPUT>;
        close(INPUT);
}

I create 3 files (1.txt, 2.txt, 3.txt) each said:

contents
of
file
(one, two, three)

This code reads in each and puts contents in an array and then prints them:

use strict;
use warnings;
my $x;
undef($/);
my @cArray;
for ($x=1;$x<4;$x++){
	open(INPUT,"<$x\.txt");
	while(<INPUT>){
	  $cArray[$x-1]=$_;
	}
	close INPUT;
}

for (@cArray){
	print "$_";
	print "-------\n";
}

Output:

contents
of
file
one
-------
contents
of
file
two
-------
contents
of
file
three
-------

Okay, this is not a great suggestion but if I had to do this TONIGHT and couldn't wait for a better idea, I'd try joining each file into one long string (with some separator, like, oh, newline or something) and putting them into an array of scalars. Then when you want to handle them, you can split each string back into an array, and do your thing.

I'm only doing it this way because it's been ages since I really used perl for anything and I can't think of how to make a proper multidimensional array, which is what you're really looking for, or if there even is such a thing in perl. (I think there was some pseudo-multidim array, and I can't remember the trick of it)

There's probably a better way, but I suspect that this is One Way To Do It.

This code will read multiple files in a directory.

opendir(DIRC, $input) || die ("canot open dir");
@files=(readdir(DIRC));
@chap_files = grep(/(.*?).txt/, @files);
foreach(@chap_files)
{
($book_name)=$_ =~ /(.*?)/;
$filename = $_;
open (FILE1, $input . "\\" . $filename) || die "canot open the file";
while(<FILE1>)
{
print $_;
}

This article has been dead for over six months. Start a new discussion instead.