in reply to CSV String Split
afoken is correct about using a Module to parse csv data, and your particular data supports that choice, because of the embedded commas within quoted fields. Here's an example using Text::CSV on your data, including a header row--in case you need to handle that (omit, otherwise):
use strict; use warnings; use Text::CSV; my $csvData = <<END; col0,col1,col2,col3,col4,col5,col6,col7 ,"value",,"value1,value2","anothervalue","oh,comeon",,"Givemeabreak" END my $csv = Text::CSV_XS->new( { binary => 1, auto_diag => 2 } ) or die "Cannot use CSV: " . Text::CSV->error_diag(); # Open the string like a file for reading open my $csvfh, '<', \$csvData or die $!; # Get first line (array reference to parsed column names) my $columnNames = $csv->getline($csvfh); # $row contains an array reference to the parsed csv line while ( my $row = $csv->getline($csvfh) ) { print "Col$_: $row->[$_]\n" for 0 .. 7; } close $csvfh;
Output:
Col0: Col1: value Col2: Col3: value1,value2 Col4: anothervalue Col5: oh,comeon Col6: Col7: Givemeabreak
An array reference to the parsed csv line's data is returned to $row which is later dereferenced using the arrow operator; e.g., $row->[0] contains the value of column zero.
Hope this helps!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: CSV String Split
by jcleland (Acolyte) on Nov 17, 2012 at 20:38 UTC | |
by jcleland (Acolyte) on Nov 17, 2012 at 21:00 UTC |