Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

List Splitter / Unmerge List

by CharlesClarkson (Curate)
on Feb 05, 2002 at 00:02 UTC ( #143322=snippet: print w/replies, xml ) Need Help??

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

    } else {
        my $padded = $qty - @$list_ref % $qty;
        push @{ $list_ref }, ($pad) x $padded;
        push @{ $return[$_ % $qty] }, $list_ref->[$_] for 0 .. $#$list
        pop @$list_ref for 1 .. $padded;
    return @return if wantarray;
    return \@return;
Replies are listed 'Best First'.
Re: List Splitter
by belg4mit (Prior) on Feb 05, 2002 at 00:10 UTC
    IIRC the conventional name for this is unmerge. At least that's what the RFC used. Also the use of split in the name is a bit confusing here as I would have expected such a thing to give:
    ([qw(apples oranges bananas)], [qw(pears berries apricots)]);
    I could also see zip and unzip being used (to highlight the interlacing).

    perl -pe "s/\b;([st])/'\1/mg"

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://143322]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (5)
As of 2020-10-01 05:06 GMT
Find Nodes?
    Voting Booth?
    If at first I donít succeed, I Ö

    Results (174 votes). Check out past polls.