my ($i,%x); $i=0; $x{$_}[$i++%3]++ for split //, $a; for my $k (sort keys %x){ my $aref = $x{$k}; print "$k "; print for @$aref; print $_; }