use strict; use warnings; my $str="A: Gold, Black, Purple, Blue, Red B: Black, Neon Pink, Neon Yellow, Neon Green, Neon Purple, Red, White, Neon Orange, Navy"; # create a hash using the A:, B: parts as keys and the following strings as values my %str = grep { $_ } map { s/^\s+//; s/\s+$//; $_; } split /([A-Z]:)/, $str; # iterate the hash and make the value strings to # arrayrefs for ( sort keys %str ) { $str{$_} = [ split /, /, $str{$_} ]; } # output for ( sort keys %str ) { print "Array $_ ", join (", ", @{$str{$_}}), "\n"; }