CUFP
CharlesClarkson
snippet
<div class="Description"><p>This routine splits a list into more than one list.</p>
<code>my @arr = qw ( apples oranges bananas pears berries apricots );
my @arr_of_columns = split_list( \@arr, 2 );
</code>
giving us:<br>
<code> ['apples', 'bananas','berries', 'prunes']
['oranges','pears', 'apricots']
</code>
<p>If you want to pad the end of uneven arrays place the padding as the third argument</p>
<code>my $arr_of_arr = split_list( [ 1 .. 7 ], 3, undef );
</code>
which gives:<br>
<code> [1,4,7]
[2,5,undef]
[3,6,undef]
</code>
<p>A note of caution: The original array is left intact. If <code>split_list</code> is used on <em>large</em> arrays you could run out of memory before this task completes.</p>
<p><b>Update:</b>Changed title to mention <em>unmerge</em>. Thanks, [belg4mit]</p></div>
<CODE>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;
}</CODE>