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

H. Wade Minter dev@trilug.org
Mon, 14 Jan 2002 13:14:24 -0500 (EST)


On Mon, 14 Jan 2002, Jeremy P wrote:

> 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:

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