Well-formed CSV quotes fields that contain a comma as part of the value. If your CSV is well-formed use the Text::CSV
module:
use Text::CSV;
my $csv = Text::CSV->new();
while (my $row = $csv->getline(\*DATA)) {
my $name = $row->[0];
my $age = $row->[1];
my @items = split /,/, $row->[2];
my $available = $row->[3];
print "$name/$age/@items/$available\n";
}
__DATA__
Name,Age,Items,Available
John,29,"laptop,mouse",Yes
Jane,28,"desktop,keyboard,mouse",yes
Doe,56,"tablet,keyboard,trackpad",touchpen,Yes
Output:
Name/Age/Items/Available
John/29/laptop mouse/Yes
Jane/28/desktop keyboard mouse/yes
Doe/56/tablet keyboard trackpad touchpen/Yes
If your CSV is not well-formed you'll need to implement a custom parse based on knowledge of your data. Assuming that the Items column is the only multi-valued field you can split on a comma and then remove the fields with a known position. Whatever is left is the items.
while (my $line = <DATA>) {
chomp $line;
my @record = split /,/, $line;
my $name = shift @record;
my $age = shift @record;
my $available = pop @record;
my @items = @record;
print "$name/$age/@items/$available\n";
}
__DATA__
Name,Age,Items,Available
John,29,laptop,mouse,Yes
Jane,28,desktop,keyboard,mouse,yes
Doe,56,tablet,keyboard,trackpad,touchpen,Yes
Alternately, you could use array slicing to get the same result:
my ($name, $age, $available, @items) = @record[0, 1, -1, 2 .. @record - 2];