my %files; foreach my $CDR (@RECList) { my ($filename,$row)= split(/,/, $CDR); $files{ $filename } ||= []; # start with empty array push @{ $files{ $filename }}, $row; # append row to that array }; # Now print out the data for my $filename (sort keys %files) { open my $csv_fh, '>>', "/ClientRrecord/$filename.csv") or die "couldn't open [$filename.csv]\n".$!; print { $csv_fh } map { "$_\n" } @$row; # print out all lines (with newlines) };