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

how do i use the split function to separate fields delimited by ","? These fields are not just delimited by a comma, but double quote comma double quote. thanx randy

Replies are listed 'Best First'.
RE: newbie split question
by lhoward (Vicar) on May 05, 2000 at 20:00 UTC
    You may want to look at the Text::CSV perl module. It already has all the logic built into it to handle CSV (Comma Separated Value) files automatically. If you want to access the file as an SQL database, take a look at DBI in conjunction with DBD::CSV.
Re: newbie split question
by ZZamboni (Curate) on May 05, 2000 at 20:25 UTC
    You may also want to take a look at Text::ParseWords, it knows how to split taking quotes into account, preserving escaped characters, etc.
Re: newbie split question
by athomason (Curate) on May 05, 2000 at 19:56 UTC
    Use something like /\",\"/ for your regexp. Be careful, though... presumably your string looks like '"alpha","beta","gamma"'. Using split will leave the leading and trailing double quote on the first and last elements, respectively. For example:
    #!/usr/local/bin/perl my @items = split /\",\"/, '"alpha","beta","gamma"'; foreach (@items) { print "$_\n"; }
    will spit out
    "alpha beta gamma"
    Just make sure you deal with those at some point; I'd probably do something like substr $string, 1, -1 If there's extra garbage in the string, maybe like <CODE>s/\"(.*)\"/$1/</CODE
      Or...
      <code> $string = "\"Foo\",\"Bar\",\"Baz\""; # Split by comma instead... @words = split(/,/, $sting); # ..and then remove the quotes foreach $word (@words) { $word =~ s/"//sg; }
        But that requires a change to the string, in which case you would just make the string more straight forward with a simpler separator.
RE: newbie split question
by Adam (Vicar) on May 05, 2000 at 19:57 UTC
    grep {tr/\"//d, print $_ . ' '}( split /\",\"/, q["Just","Another","Perl","Hacker"] )
Re: newbie split question
by Anonymous Monk on May 06, 2000 at 20:24 UTC
    Taken from "perl cookbook", use Text::ParseWords; sub parse_csv { return quotewords(",",0, $_[0]; }
RE: newbie split question
by Anonymous Monk on May 07, 2000 at 22:04 UTC
    @new_array = split(/,",/, $line_you_want_to_split); $line_you_want_to_split would of course be a scalar that contains the,,,line you want to split up ;) @new_array will be the,,, new array that's created.