/
CSV.pm
214 lines (196 loc) · 6.76 KB
/
CSV.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#use Grammar::Tracer;
grammar Text::CSV::File {
regex TOP { ^ <line>+ % "\n" <empty_line>* $ }
regex line { <value>+ % ',' }
regex value {
<before ','> | <pure_text>
| [\h* \"] ~ [\" \h*] <quoted_contents>
}
regex quoted_contents { [ <pure_text> | ',' | \s | '""' ]* }
regex pure_text { [<!before <[",]>> \N]+ }
regex empty_line { \h* \n }
}
class Text::CSV {
has $.trim;
has $.strict;
has $.skip-header;
has $.output;
has $.quote;
has $.separator;
my $trim-default = False;
my $strict-default = 'default';
my $skip-header-default = False;
my $output-default = 'arrays';
my $quote-default = '"';
my $separator-default = ',';
sub extract_text($m, $quote, :$trim) {
my $text = ($m<quoted_contents> // $m).subst("$quote$quote", $quote, :global);
return $trim ?? $text.trim !! ~$text;
}
method parse($input, :$trim is copy, :$strict is copy,
:$skip-header is copy, :$output is copy,
:$separator is copy, :$quote is copy) {
if self.defined {
$trim //= $.trim // $trim-default;
$strict //= $.strict // $strict-default;
$skip-header //= $.skip-header // $skip-header-default;
$separator //= $.separator // $separator-default;
$quote //= $.quote // $quote-default;
if $output === Any {
$output = $.output // $output-default;
}
}
else {
$trim //= $trim-default;
$strict //= $strict-default;
$skip-header //= $skip-header-default;
$separator //= $separator-default;
$quote //= $quote-default;
if $output === Any {
$output = $output-default;
}
}
if $output ~~ Str {
$output = $output.lc;
}
if my $check = check_ok($quote, $separator) {
die $check;
}
my $parser = Text::CSV::File;
if $quote ne $quote-default or $separator ne $separator-default {
grammar CustomCSV is Text::CSV::File {
regex line { <value>+ % $separator }
regex value {
<before $separator> | <pure_text> |
$quote ~ $quote <quoted_contents>
}
regex quoted_contents {
[ <pure_text> | $separator | <[\r\n]> |
' ' | $quote$quote ]*
}
regex pure_text { [<!before [$quote | $separator]> \N]+ }
}
$parser = CustomCSV;
}
$parser.parse($input)
or die "Sorry, cannot parse";
my @lines = $<line>.list;
my @values = map {
[map { extract_text($_, $quote, :$trim) }, .<value>.list]
}, @lines;
if $strict eq 'default' {
$strict = !$output || $output !~~ 'arrays';
}
if $strict {
my $expected-columns = @values[0].elems;
for ^@values -> $line {
if (my $c = @values[$line]) > $expected-columns {
die "Too many columns ($c, expected $expected-columns) "
~ "on line $line";
}
elsif $c < $expected-columns {
die "Too few columns ($c, expected $expected-columns) "
~ "on line $line";
}
}
}
if $output && $output eq 'hashes' {
my @header = @values.shift.list;
my @results;
my $i = 0;
for @values -> @line {
my %hash = map { @header[$_] => @line[$_] }, ^(+@line min +@header);
@results[$i++] = %hash;
}
@values = @results;
}
elsif $output && $output eq 'arrays' {
if $skip-header {
@values.shift;
}
}
else {
my $type = $output;
my @header = @values.shift.list;
@values = map -> @line {
my %attrs = map {; @header[$_] => @line[$_] },
^(+@line min +@header);
$type.new( |%attrs );
}, @values;
}
return @values;
}
method parse-file($filename, *%_) {
return self.parse( slurp($filename), |%_ );
}
}
our sub csv-write ( @csv, :$header = '', :$separator is copy = ',',
:$always_quote, :$quote is copy = <"> ) is export {
if my $check = check_ok($quote, $separator) {
die $check;
}
my @header = $header ?? @$header !! ();
my $first = @csv[0];
my @csv-quoted;
if $first ~~ Array { # AoA
if @header.elems {
add( @header );
}
for @csv -> $line {
add( @$line );
}
}
elsif $first ~~ Hash { # AoH
unless @header.elems {
die "Can not guarantee order of columns if no header is provided";
}
add( @header );
for @csv -> $line {
add( %$line{@header} );
}
}
elsif $first ~~ Cool { # Assume it is just an array of strings
if @header.elems { # A header doesn't make much sense here,
add( @header); # but it is probably better to allow it
}
add( @csv );
}
else { # AoO
unless @header.elems {
die "You need to provide a header array of accessors";
}
add( @header );
for @csv -> $object {
@csv-quoted.push: (join $separator, map { csv-quote $object."$_"() }, @header);
}
};
return @csv-quoted.join("\n");
sub add(@list) {
@csv-quoted.push: (join $separator, map { csv-quote $_ }, @list);
}
sub csv-quote ($str is copy = '') {
if $always_quote or $str ~~ / $quote | $separator | \r | \n / {
$str = $quote ~ $str.subst($quote, $quote ~ $quote, :g) ~ $quote;
}
$str
}
}
our sub csv-write-file (@csv, :$file, *%_) is export {
die "Must provide an output file name" unless $file.defined;
my $fh = open($file, :w) or die $!;
$fh.print( csv-write( @csv, |%_ ) );
$fh.close or die $!;
}
sub check_ok ($quote, $separator) {
return "Sorry, can not use a space as a quoting character"
if $quote ~~ /\s/;
return "Sorry, can not use a newline as a separator character"
if $separator ~~ /\n/;
return "Sorry, only single character separators are supported"
if $separator.chars != 1;
return "Sorry, only single character quotes are supported"
if $quote.chars != 1;
return "Sorry, you can't use the same character for separator AND quote."
if $quote eq $separator;
}
# vim:ft=perl6