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

I've come across a situation where I'd like to split a string at commas - pretty simple using split. BUT I don't want to split the string at commas that are between two double quotes. For instance, if I have the string:

a,"b,c",d

I want an array with the elements:

a
b,c
d

Is there an easy way to do this with regular expressions? Or will I have to write a function to manually read through the string and split it?

Replies are listed 'Best First'.
Re: Regex and split()
by btrott (Parson) on Apr 26, 2000 at 10:43 UTC
Re: Regex and split()
by perlmonkey (Hermit) on Apr 26, 2000 at 07:40 UTC
    I dont know if there is a way to do this with split. If there is I hope someone will post.

    Since you are parsing on ',' I think the easiest way is to let perl handle it naturally with an eval statement.
    Since perl would normally intrepret (a, "b,c", d) as an array of three elements (what we are looking for in this case) just let it do its thing.
    $str = 'a, "b,c", d'; @array = eval('('.$str.')');
    One obvious problem is that is will throw away white space unless it is contained in "". But you could probably fix that if you wanted.
    I dont know how robust this solution is, but it works for your example. It should be fairly stable though, as long as you catch the eval errors.
    #!/usr/bin/perl #set string to split on "," my $str = 'a,"b,c",d'; #use perl to parse an array as it normally would # # after the eval this next line will look like: # my @a = (a,"b,c",d); # # so $a[0] = 'a', $a[1] = 'b,c', and $a[2] = 'd' my @array = eval("(".$str.")"); #catch errors from eval if( $@ ) { die "eval error: $@\n"; } #print out the results. foreach (@array) { print $_, "\n"; }