How do I convert

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.

--

when small people start casting long shadows, it is time to go to bed

In reply to rearranging an array of arrays by punkish

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.