use strict; my @output; while(){ chomp; next unless $_ =~ /\S/; # push any quoted stuff (incl. quotes) onto array... (we assume that all quotes are paired) push my @quoted, ($_ =~ /"([^"]*)"/g); # replace any commas in the array with '_comma_' foreach my $quote(@quoted){ $quote =~ s/,/_comma_/g; } # now replace the ',' versions with the "_comma_" versions $_ =~ s/"[^"]*"/'"' . (shift @quoted) . '"'/ge; # now we can safely split on any commas (quoted commas are now '_comma') push @output, [split /,/]; # finally, replace any '_comma_' values with ',' in the latest element of output foreach(@{$output[$#output]}){ s/_comma_/,/g; } } # what have we got? foreach(@output){ foreach(@{$_}){ print "$_:"; } print "\n"; } __DATA__ 123,456,"hello, world, goodbye, world",789 123,456,"hello, world, goodbye, world",789,"foo, bar","bar, foo" "hello, world","goodbye, world",123,"foo" "hello" 123,456,"goodbye, world",789