nebulus nebulus - 18 days ago 4x
Perl Question

How do I split a string into an array by comma but ignore commas inside double quotes?

I have a line:

$string = 'Paul,12,"soccer,baseball,hockey",white';

I am try to split this into @array that has 4 values so

print $array[2];



How do I this? Help!


In response to how to do it with Text::CSV(_PP). Here is a quick one.


use strict;
use warnings;

use Text::CSV_PP;
my $parser = Text::CSV_PP->new();

my $string = "Paul,12,\"soccer,baseball,hockey\",white";

my @fields = $parser->fields();

print "$_\n" for @fields;

Normally one would install Text::CSV or Text::CSV_PP through the cpan utility.

To work around your not being able to install modules, I suggest you use the 'pure Perl' implementation so that you can 'install' it. The above example would work assuming you copied the text of Text::CSV_PP source into a file named in a folder called Text created in the same directory as your script. You could also put it in some other location and use the use lib 'directory' method as discussed previously. See here and here to see other ways to get around install restriction using CPAN modules.