Skip to content

Instantly share code, notes, and snippets.

@mca-gif
Created August 29, 2012 23:18
Show Gist options
  • Save mca-gif/3520207 to your computer and use it in GitHub Desktop.
Save mca-gif/3520207 to your computer and use it in GitHub Desktop.
Perl function for parsing a CSV into an array of elements
This is much slower than a RegEx, however it handles commas inside of quoted string values.
sub ParseCSVLine($line) {
chomp($line);
@myChars = split(//, $line);
@myFields = ();
$newField = "";
$inQuote = 0;
$inEsc = 0;
foreach $c (@myChars) {
if ( $c eq "\\" ) {
if ( $inEsc == 0 ) {
$inEsc = 1;
} else {
$inEsc = 0;
$newField = $newField . "\\";
};
} elsif ( $c eq "\"" ) {
if ( $inEsc == 1 ) {
$inEsc = 0;
$newField = $newField . "\"";
} elsif ( $inQuote == 0 ) {
$inQuote = 1;
} else {
$inQuote = 0;
};
} elsif ( $c eq "," ) {
if ( $inEsc == 1 ) {
$inEsc = 0;
$newField = $newField . ",";
} elsif ( $inQuote == 1 ) {
$newField = $newField . ",";
} else {
push(@myFields, $newField);
$newField = "";
};
} else {
$newField = $newField . $c;
};
};
# Puts the last field on the stack
push(@myFields, $newField);
return @myFields;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment