spacegeologist has asked for the wisdom of the Perl Monks concerning the following question:

I am using split to separate array elements. The data looks like this:

1, 2, 3,"a,b,c","d", 4, ect...

I need it to be separated like this:

1

2

3

a,b,c

d

4

I've tried  split /,\s+|,"/ but the results are inconsistent. I need use commas as the delimiter except when they are surrounds by quotes. Any ideas?

Replies are listed 'Best First'.
Re: Incosistent delimeter
by toolic (Bishop) on Apr 21, 2011 at 01:48 UTC
    Text::CSV and similar offerings from CPAN were made to tackle this problem.
Re: Incosistent delimeter
by trwww (Priest) on Apr 21, 2011 at 02:25 UTC
    $ cat csv.pl use warnings; use strict; use Text::CSV; use Data::Dumper; my $data = q|1, 2, 3,"a,b,c","d", 4|; my $csv = Text::CSV->new( {allow_whitespace => 1} ); $csv->parse($data); my @data = $csv->fields; print Dumper( \@data ), "\n"; $ perl csv.pl $VAR1 = [ '1', '2', '3', 'a,b,c', 'd', '4' ];

    Don't forget exception handling!

Re: Inconsistent delimeter
by cmac (Monk) on Apr 21, 2011 at 02:30 UTC
    It's not clear what you want to do about spaces around commas. This strips spaces before and after commas:
    $data = '1, 2, 3,"a,b,c","d", 4'; @a = $data =~ / *(".*?"|[^,]*?) *(?:,|$)/g; pop @a; for (@a) {s/^"(.+?)"$/$1/} print join "\n", @a;