[Dev] perl: how to parse quoted comma separated values?
Jeremy P
dev@trilug.org
Mon, 14 Jan 2002 14:08:24 -0500 (EST)
On Mon, 14 Jan 2002, Dana Smith wrote:
> 2) On google I found Text::CSV
Thanks for the tip (thanks to Greg too). This is what I ended up using...
it's really quite a simple module and works well for my purpose.
> 3) The book "Mastering Regular Expressions" contains this magic:
>
> sub parse_csv {
> my $text = shift; # record containing comma-separated values
> my @new = ();
>
> # the first part groups the phrase inside the quotes.
> # see explanation of this pattern in MRE
> push(@new, $+) while $text =~ m{"([^\"\\]*(?:\\.[^\"\\]*)*)",? | ([^,]+),? | ,}gx;
> push(@new, undef) if substr($text, -1,1) eq ',';
> return @new; # list of values that were comma-separated
Ugh. I promise I'm not really "afraid" of regular expressions, but it
stuff like this sure is hard to read!
--Jeremy