Subject: [Dev] perl: how to parse quoted comma separated values?

From: Jeremy P <[email-masked]>
Date: Mon, 14 Jan 2002 13:09:18 -0500 (EST)

Hi TriLug dev types,

Hope this question is appropriate for this forum.  I'm not a real
developer-type, but I use scripting to help various system admin tasks.  
For a particular task, I need to parse in records from a CSV
(comma-separated values) file using perl.  The data files have records
like this:

"King, Jr","Martin","Luther","etc"
"Washington","George",,"foo"

I'd like to each record into an array, getting rid of the double-quotes
and the ',' delimiters in the process.

Obviously a simple statement like this won't work:
	@fields = split(',');
because of the fields with commas in the data ("King, Jr")

I can't do things that match on '","' because that wouldn't apply to the
empty fields or the first and last fields.

Anyone done simple parsing like this before?  Is there something glaringly
obvious that I'm missing?  I poked around on CPAN and there are a bunch of
CSV routines, including even a DBD driver, but that seems way overkill.  
Maybe I should just delve into using one of those modules.

Thanks for any advice,

Jeremy Portzer
Durham Tech Community College

---

From: "H. Wade Minter" <[email-masked]>
Date: Mon, 14 Jan 2002 13:14:24 -0500 (EST)

> (comma-separated values) file using perl.  The data files have records

I used a regexp on a hacked-together thing I did one time - I knew exactly
how many fields were coming in, etc.  It looked something like:

while ($line = <LOGFILE>)
{
  chomp ($line);
  $line =~ /"(.*?)"\s+"(.*?)"\s+"(.*?)"/;

  $firstfield = $1;
  $secondfield = $2;
  ....
}

I'm sure there's a better way, though.

--Wade

---

From: "M. Mueller/bhu5nji" <[email-masked]>
Date: Mon, 14 Jan 2002 07:32:01 -0500

> (comma-separated values) file using perl.  

I've been getting some phenomenal productivity using Python.  I had to make a 
choice between PERL and Python a month ago.  From a Python perspective you 
can get things like this:

http://object-craft.com.au/projects/csv/

Mike