Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Incosistent delimeter

by spacegeologist (Initiate)
on Apr 21, 2011 at 01:31 UTC ( [id://900449]=perlquestion: print w/replies, xml ) Need Help??

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;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://900449]
Approved by toolic
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-04-20 00:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found