my @groups; my %in_num_groups; while (@pile) { my $item = shift @pile; push @{$groups[$in_num_groups{$item}++]}, $item; }