http://www.perlmonks.org?node_id=1045472


in reply to Splitting Multiple files into arrays.

But the following code below is not working.
    push @{ "table$i"}

That's because you're trying to build a string and use it as an array ref. I strongly urge you to re-think your need to put everything into @array1, @array2, ...; this sort of logic is almost never a good idea. Use an array of array refs instead:

use 5.012; use warnings; use autodie; my @array; for (glob 'file*.txt') { local $/; # Slurp my ($num) = /(\d+)\.txt$/g; open my $fh, '<', $_; $array[$num] = [ split /\s/m, <$fh> ]; } $" = '> <'; say "\$array[$_] = <@{$array[$_]}>" for 1..$#array;

Output:

$array[1] = <foo> <bar> <baz> $array[2] = <one> <two> <three> <four> <five> <six> $array[3] = <apple> <pear> <mango>

But even at that, you may want to consider a hash of filenames, instead, as a more general solution:

my %hash; for my $file (glob 'file*.txt') { local $/; # Slurp open my $fh, '<', $file; $hash{$file} = [ split /\s/m, <$fh> ]; } $" = '> <'; say "\$hash[$_] = <@{$hash{$_}}>" for keys %hash;

Input files used

file1.txt: foo bar baz file2.txt: one two three four five six file3.txt: apple pear mango

Replies are listed 'Best First'.
Re^2: Splitting Multiple files into arrays.
by devbond (Novice) on Jul 21, 2013 at 11:07 UTC
    I have a 2D File like the following and i have 8 such files which i have to put into 8 Arrays. 00:00 2453 10319 0 0 01:00 1565 626 0 0 02:00 1171 4195 0 0 03:00 1117 3597 4 0 04:00 1494 569 0 0 05:00 2873 0900 0 0 06:00 4899 2368 0 0 07:00 4251 9664 0 0 08:00 5791 8910 0 0 09:00 7068 0138 0 0 10:00 8464 3881 0 0 11:00 9610 5291 0 0 12:00 1017 8634 0 0 13:00 1090 8203 0 0 14:00 1322 9165 0 0

      That data is tab-delimited, not space-delimited. I'd use Text::CSV for this.

      use Text::CSV; my $csv = Text::CSV->new({ sep_char = "\t" }); my $array_ref = $csv->getline_all($fh); # OR... my @array = @{ $csv->getline_all($fh) };

      You can easily adapt the loop constructs I suggested, above, or many of the other suggestions given by others, with this approach. Good luck.