Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Destructive Unmerge List

by CharlesClarkson (Curate)
on Feb 06, 2002 at 10:07 UTC ( #143591=snippet: print w/ replies, xml ) Need Help??

Description:

This routine unmerges a list into more than one list, but destroys the original list. A non-destructive version is available.

my @arr = qw ( apples oranges bananas pears berries apricots peaches ) +; my @arr_of_columns = unmerge_list_d( \@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 = unmerge_list_d( [ 1 .. 7 ], 3, 'goofy' );
which yields:
[ [1, 4, 7] [2, 5, 'goofy'] [3, 6, 'goofy'] ]

I don't know if unmerge_list_d will allow very large arrays to be unmerged, but it should help reduce memory usage.

sub unmerge_list_d {
    my ( $list_ref, $qty, $pad ) = @_;
    return unless ref $list_ref eq 'ARRAY';
    my $arr;
    push @$arr, [] for 1 .. $qty;

    if ( @$list_ref % $qty &&  @_ > 2) {
        my $padded = $qty - @$list_ref % $qty ;
        push @{ $list_ref }, ($pad) x $padded;
    }

    LOOP:
    while (1) {
        foreach ( @$arr ) {
            push @{ $_ }, shift @$list_ref;
            last LOOP unless @$list_ref;
        }
    }

    return @$arr if wantarray;
    return $arr;
}
Comment on Destructive Unmerge List
Download Code

Back to Snippets Section

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (12)
As of 2015-07-31 10:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (276 votes), past polls