Perl FAQ 4.28: How can I split a [character] delimited string except when inside

Perl FAQ 4.28

How can I split a [character] delimited string except when inside

[character]?

I'm trying to split a string that is comma delimited into its different fields. I could easily use split(/,/), except that I need to not split if the comma is inside quotes. For example, my data file has a line like this:

    SAR001,"","Cimetrix, Inc","Bob Smith","CAM",N,8,1,0,7,"Error, Core Dumped"

Due to the restriction of the quotes, this is a fairly complex solution. However, we thankfully have Jeff Friedl* to handle these for us. He suggests (assuming that your data is contained in the special variable $_):

    undef @field;
    push(@fields, defined($1) ? $1:$3) 
	while m/"([^"\\]*(\\.[^"\\]*)*)"|([^,]+)/g;


Other resources at this site: