Created
August 29, 2012 23:18
-
-
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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