my $foo = [ [1, 2, 3, ...], ['a', 'b', 'c', ...], ['foo', 'bar', 'baz', ...], ];
into
my $bar = [ [1, 'a', 'foo', ...], [2, 'b', 'bar', ...], [3, 'c', 'baz', ...], ];
The component arrays in the input array 'foo' can be of different lengths, so component arrays in the output array 'bar' should have a zero-length string '' for missing values.
Here is what I came up with...
my $bar = rearrange($foo); sub rearrange { my ($in) = @_; my @out; for my $col ( 0 .. (max($arrays) - 1) ) { my @row; foreach my $arr (@$in) { push @row, defined($arr->[$col]) ? $arr->[$col] : ''; } push @out, \@row; } return \@out; } sub max { my ($arr) = @_; my $max; foreach my $array (@$arr) { $max = scalar @$array if (scalar @$array > $max); } return $max; }
Oh, and component arrays in $foo could be pretty large... million elements or so each, and 30 or more such arrays.
Note: Original problem -- I have 30 or so text files with a million or so rows in each. Each text file has values destined for a column in a table in a db. So, a table with 30 or so columns and a million or so rows. The rows in the text files are ordered... they go in the same order in the table. In other words, row 'n' in each text file is a column value for the nth row in the table. How do I populate that table?
So, I thought I would build an array of arrays representing the table, and then INSERT the aofa into the table. Better suggestions are welcome, but I am also academically curious about the problem of rearranging an array.
In reply to rearranging an array of arrays by punkish
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |