use warnings; use strict; my $l = 'abc,2,3,4,5,6 abc,7,5,2,1,6,2,3 abc,8,2,1,3,1,4 ....... def,8,9,4,5,6 def,5,6,2,1 '; my %hash; my $k; for (split/[,. ]+/ => $l){ if(/\D+?/){ $k = $_ }else{ push @{$hash{$k}},$_ } } print $_,',',join (',' => @{$hash{$_}}),$/ for sort keys %hash;