for my $pair (sort($str =~ /([^,]*,[^,]*)(?:,|$)/g)) { my ($k, $v) = split /,/, $pair; ... }