Browse files

[CSV] refactor to use a grammar

Wow, where'd all the code go?
  • Loading branch information...
1 parent 19d5da4 commit 835db1bafe2c0e3dc11689f45ae1d44709b76ee4 @masak committed Aug 15, 2009
Showing with 24 additions and 15 deletions.
  1. +24 −15 lib/CSV.pm
View
39 lib/CSV.pm
@@ -1,25 +1,34 @@
+grammar CSV::Line {
+ rule TOP { ^ <value> ** ',' $ }
+ rule value {
+ | <pure_text>
+ | \' <single_quote_contents> \'
+ | \" <double_quote_contents> \"
+ }
+ regex single_quote_contents { <pure_text> ** [\"|' '] }
+ regex double_quote_contents { <pure_text> ** [\'|' '] }
+ regex pure_text { <alnum>+ }
+}
+
class CSV {
- sub parse-quotes($_ is copy) {
- if $_ ~~ /^\' (.*) \'$/ {
- $_ = ~$0;
- }
- if $_ ~~ /^\" (.*) \"$/ {
- $_ = ~$0;
- }
- if $_ ~~ /<!before \\>[\\\\]*\'/ {
- die "Cannot have unquoted single quotes in value: ", $_;
- }
- if $_ ~~ /<!before \\>[\\\\]*\"/ {
- die "Cannot have unquoted double quotes in value: ", $_;
- }
- return $_;
+ sub extract_text($m) {
+ return ($m<single_quote_contents>
+ // $m<double_quote_contents>
+ // $m).Str;
+ }
+
+ sub parse_line($line) {
+ CSV::Line.parse($line)
+ or die "Sorry, cannot parse: ", $line;
}
method read($input) {
my @lines = $input.split("\n");
if @lines[*-1] ~~ /^ \s* $/ {
@lines.pop;
}
- return map { [map { parse-quotes(.trim) }, .split(/','/)] }, @lines;
+ return map {
+ [map { extract_text($_) }, parse_line($_)<value>]
+ }, @lines;
}
}

0 comments on commit 835db1b

Please sign in to comment.