# build a hash to mash all of the fruits together. # foreach my $row (@$matrix_ref) { # add the some_col to the fruit push(@{$tmp_hash->{$row[0]}}, $row[1]); } my $output; my $i; foreach my $fruit (keys(%$tmp_hash)) { # make the fruit the first element of the sub array push(@{$output->[$i]}, $fruit); # push the some_col's onto the array push(@{$output->[$i]}, @{$tmp_hash->{'fruit'}}; # start creating the next sub array $i++; } #output should now be what you want.