This routine splits a list into more than one list.

my @arr = qw ( apples oranges bananas pears berries apricots ); my @arr_of_columns = split_list( \@arr, 2 );
giving us:
['apples', 'bananas','berries', 'prunes'] ['oranges','pears', 'apricots']

If you want to pad the end of uneven arrays place the padding as the third argument

my $arr_of_arr = split_list( [ 1 .. 7 ], 3, undef ); which gives:
[1,4,7] [2,5,undef] [3,6,undef]

A note of caution: The original array is left intact. If split_list is used on large arrays you could run out of memory before this task completes.

Update:Changed title to mention unmerge. Thanks, belg4mit

sub split_list { use integer; my ( $list_ref, $qty, $pad ) = @_; return unless ref $list_ref eq 'ARRAY'; my @return; if ( !( @$list_ref % $qty ) || @_ == 2 ) { push @{ $return[$_ % $qty] }, $list_ref->[$_] for 0 .. $#$list +_ref; } else { my $padded = $qty - @$list_ref % $qty; push @{ $list_ref }, ($pad) x $padded; push @{ $return[$_ % $qty] }, $list_ref->[$_] for 0 .. $#$list +_ref; pop @$list_ref for 1 .. $padded; } return @return if wantarray; return \@return; }

In reply to List Splitter / Unmerge List by CharlesClarkson

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.