Browse files

trimming of spaces is now an option

One uses :trim to turn it on.
  • Loading branch information...
1 parent 2a05957 commit 3e71665115b2428aee64ccbaa74df3d454549f87 @masak committed Aug 20, 2009
Showing with 22 additions and 22 deletions.
  1. +7 −2 README
  2. +0 −8 TODO
  3. +9 −8 lib/Text/CSV.pm
  4. +6 −4 t/02-commas.t
View
9 README
@@ -1,9 +1,14 @@
Simple CSV (comma-separated values) format parser for Perl 6.
use v6;
- use CSV;
+ use Text::CSV;
- say CSV.read-file('somefile.csv').perl;
+ say Text::CSV.read-file('somefile.csv').perl;
+ say Text::CSV.read("foo,bar\nbaz,boo").perl;
+
+Oh, and the C<read> methods take this flag:
+
+ :trim Removes whitespace on both ends of each value
== License
View
8 TODO
@@ -1,13 +1,5 @@
Some new ideas await tuits:
-* According to <http://en.wikipedia.org/wiki/Comma-separated_values>,
- "In some CSV implementations, leading and trailing spaces or tabs,
- adjacent to commas, are trimmed. This practice is contentious and in
- fact is specifically prohibited by RFC 4180, which states, "Spaces are
- considered part of a field and should not be ignored." Seems a wise
- course of action is to make spaces and tabs significant by default,
- but add a 'trim' flag to the class.
-
* Similarly, make single quotes not quote things by default. Perhaps
not even a flag is needed in this case.
View
17 lib/Text/CSV.pm
@@ -11,28 +11,29 @@ grammar Text::CSV::Line {
}
class Text::CSV {
- sub extract_text($m) {
- return ($m<single_quote_contents>
- // $m<double_quote_contents>
- // $m).Str;
+ sub extract_text($m, :$trim) {
+ my $text = ($m<single_quote_contents>
+ // $m<double_quote_contents>
+ // $m).Str;
+ return $trim ?? $text.trim !! $text;
}
sub parse_line($line) {
Text::CSV::Line.parse($line)
or die "Sorry, cannot parse: ", $line;
}
- method read($input) {
+ method read($input, :$trim) {
my @lines = $input.split("\n");
if @lines[*-1] ~~ /^ \s* $/ {
@lines.pop;
}
return map {
- [map { extract_text($_) }, parse_line($_)<value>]
+ [map { extract_text($_, :$trim) }, parse_line($_)<value>]
}, @lines;
}
- method read-file($filename) {
- return self.read( slurp($filename) );
+ method read-file($filename, *%_) {
+ return self.read( slurp($filename), |%_ );
}
}
View
10 t/02-commas.t
@@ -3,10 +3,6 @@ use Test;
use Text::CSV;
-sub ok_becomes($input, $output, $description = '') {
- is_deeply Text::CSV.read($input), $output, $description;
-}
-
is_deeply Text::CSV.read(q[[[foo,bar,baz
foo,bar , baz
foo,bar , baz]]]),
@@ -15,6 +11,12 @@ foo,bar , baz]]]),
['foo', 'bar ', ' baz'] ],
'spaces are not trimmed by default';
+is_deeply Text::CSV.read(q[[[foo,bar,baz
+foo,bar , baz
+foo,bar , baz]]], :trim),
+ [ [<foo bar baz>] xx 3 ],
+ 'spaces are trimmed when :trim is passed';
+
done_testing;
# vim:ft=perl6

0 comments on commit 3e71665

Please sign in to comment.