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