-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathText-CSV.man
2543 lines (1823 loc) · 86.6 KB
/
Text-CSV.man
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
STDIN(1) User Contributed Perl Documentation STDIN(1)
[1mDISCLAIMER[0m
Note that updating these docs is an ongoing process and some perl5
idioms might not have been translated yet into correct raku idiom. My
bad. Sorry. (Feedback welcome)
[1mNAME[0m
Text::CSV - comma-separated values manipulation routines
[1mSYNOPSIS[0m
use Text::CSV;
# Read whole file in memory
my @aoa = csv(in => "data.csv"); # as array of arrays
my @aoh = csv(in => "data.csv",
headers => "auto"); # as array of hashes
# Write array of arrays as csv file
csv(in => @aoa, out => "file.csv", sep => ";");
my @rows;
# Read/parse CSV
my $csv = Text::CSV.new;
my $fh = open "test.csv", :r, :!chomp;
while (my @row = $csv.getline($fh)) {
@row[2] ~~ m/pattern/ or next; # 3rd field should match
@rows.push: @row;
}
$fh.close;
# and write as CSV
$fh = open "new.csv", :w;
$csv.say($fh, $_) for @rows;
$fh.close;
[1mDESCRIPTION[0m
Text::CSV provides facilities for the composition and decomposition of
comma-separated values. An instance of the Text::CSV class will combine
fields into a "CSV" string and parse a "CSV" string into fields.
The module accepts either strings or files as input and support the use
of user-specified characters (or sequences thereof) for delimiters,
separators, and escapes.
In all following documentation, "WIP" stands for "Work In Progress" and
"NYI" for "Not Yet Implemented". The goal is to get rid of all of
those.
[1mEmbedded newlines[0m
[1mImportant Note[22m: The default behavior is to accept only UTF-8
characters.
But you still have the problem that you have to pass a correct line to
the "parse" method, which is more complicated from the usual point of
usage:
my $csv = Text::CSV.new;
for lines() : eager { # WRONG!
$csv.parse($_);
my @fields = $csv.fields;
}
this will break for several reasons. The default open mode is to
"chomp" lines, which will also remove the newline sequence if that
sequence is not (part of) the newline at all. As the "for" might read
broken lines: it does not care about the quoting. If you need to
support embedded newlines, the way to go is to [1mnot [22mpass "eol" in the
parser (it accepts "\n", "\r", [1mand [22m"\r\n" by default) and then
my $csv = Text::CSV.new;
my $io = open $file, :r, :!chomp;
while (my $row = $csv.getline($io)) {
my @fields = @$row;
}
[1mBinary data[0m
For now, Text::CSV only accepts Unicode. Binary data is planned.
[1mSPECIFICATION[0m
While no formal specification for CSV exists, RFC 4180
<https://datatracker.ietf.org/doc/html/rfc4180> ([4m1[24m) describes the
common format and establishes "text/csv" as the MIME type registered
with the IANA. RFC 7111 <https://datatracker.ietf.org/doc/html/rfc7111>
([4m2[24m) adds fragments to CSV.
Many informal documents exist that describe the "CSV" format. "How
To: The Comma Separated Value (CSV) File Format" ([4m3[24m) provides an
overview of the "CSV" format in the most widely used applications and
explains how it can best be used and supported.
1) https://datatracker.ietf.org/doc/html/rfc4180
2) https://datatracker.ietf.org/doc/html/rfc7111
3) http://creativyst.com/Doc/Articles/CSV/CSV01.shtml
The basic rules are as follows:
[1mCSV [22mis a delimited data format that has fields/columns separated by the
comma character and records/rows separated by newlines. Fields that
contain a special character (comma, newline, or double quote), must be
enclosed in double quotes. However, if a line contains a single entry
that is the empty string, it may be enclosed in double quotes. If a
field's value contains a double quote character it is escaped by
placing another double quote character next to it. The "CSV" file
format does not require a specific character encoding, byte order, or
line terminator format.
· Each record is a single line ended by a line feed (ASCII/"LF"=0x0A)
or a carriage return and line feed pair (ASCII/"CRLF"="0x0D 0x0A"),
however, line-breaks may be embedded.
· Fields are separated by commas.
· Allowable characters within a "CSV" field include 0x09 ("TAB") and
the inclusive range of 0x20 (space) through 0x7E (tilde). In binary
mode all characters are accepted, at least in quoted fields.
· A field within "CSV" must be surrounded by double-quotes to contain a
separator character (comma).
Though this is the most clear and restrictive definition, Text::CSV is
way more liberal than this, and allows extension:
· Line termination by a single carriage return is accepted by default
· The separation, escape, and escape can be any valid Unicode sequence.
· A field in "CSV" must be surrounded by double-quotes to make an
embedded double-quote, represented by a pair of consecutive double-
quotes, valid. You may additionally use the sequence ""0" for
representation of a NULL byte. Using 0x00 is just as valid.
· Several violations of the above specification may be lifted by
passing some options as attributes to the object constructor.
[1mMETHODS[0m
[1mversion[0m
Returns the current module version.
[1mnew[0m
Returns a new instance of class Text::CSV. The attributes are described
by the optional named parameters
my $csv = Text::CSV.new(attributes ...);
The following attributes are available:
eol
my $csv = Text::CSV.new(eol => "\r\n");
$csv.eol(Str);
my $eol = $csv.eol;
The end-of-line string to add to rows for "print" or the record
separator for "getline".
When not set in a [1mparser [22minstance, the default behavior is to
accept "\n", "\r", and "\r\n", so it is probably safer to not
specify "eol" at all. Passing "Str" or the empty string behave the
same.
As raku interprets "\r\n" as a single grapheme in input, it is
dissuaded to use "\r\n" as "eol" when parsing. Please choose "Str"
instead.
When not passed in a [1mgenerating [22minstance, records are not
terminated at all, so it is probably wise to pass something you
expect. A safe choice for "eol" on output is either "\n" or "\r\n".
Common values for "eol" are "\012" ("\n" or Line Feed), "\015\012"
("\r\n" or Carriage Return, Line Feed), and "\015" ("\r" or
Carriage Return).
sep
sep_char
sep-char
separator
my $csv = Text::CSV.new(sep => ";");
$csv.sep("\x[ff0c]"); # FULLWIDTH COMMA
my $sep = $csv.sep;
The sequence used to separate fields, by default a comma: (",").
This sequence is required and cannot be disabled.
The separation sequence can not be equal to the quote sequence, the
escape sequence or the newline sequence.
See also "CAVEATS"
quote
quote_char
quote-char
my $csv = Text::CSV.new(quote => "'");
$csv.quote("\x[ff02]); # FULLWIDTH QUOTATION MARK
$csv.quote(Str);
my $quo = $csv.quote;
The sequence to quote fields containing blanks or binary data, by
default the double quote character ("""). A value of "Str" disables
quotation (for simple cases only).
The quotation sequence can not be equal to the separation sequence
or the newline sequence.
See also "CAVEATS"
escape
escape_char
escape-char
my $csv = Text::CSV.new(escape => "\\");
$csv.escape("\x[241b]"); # SYMBOL FOR ESCAPE
$csv.escape(Str);
my $esc = $csv.escape;
The sequence to escape certain characters inside quoted fields.
The "escape" defaults to being the double-quote mark ("""). In
other words the same as the default sequence for "quote". This
means that doubling the quote mark in a field escapes it:
"foo","bar","Escape ""quote mark"" with two ""quote marks""","baz"
If you change "quote" without changing "escape", "escape" will
still be the double-quote ("""). If instead you want to escape
"quote" by doubling it you will need to also change "escape" to be
the same as what you have changed "quote" to.
The escape sequence can not be equal to the separation sequence.
binary
WIP: Default is True. Non-UTF-8 real binary (Blob) does not yet
parse. Opening the resource with encoding utf8-c8 is most likely
the way to go.
my $csv = Text::CSV.new(:binary);
$csv.binary(False);
my $bin = $csv.binary;
If this attribute is "True", you may use binary data in quoted
fields, including line feeds, carriage returns and "NULL" bytes.
(The latter could be escaped as ""0".) By default this feature is
on.
Note that valid Unicode (UTF-8) is not considered binary.
strict
my $csv = Text::CSV.new(:strict);
$csv.strict(False);
my $flg = $csv.strict;
If set to True, any row that parses to a different number of
columns than the previous row will cause the parser to throw error
2014.
formula-handling
formula_handling
formula
my $csv = Text::CSV.new(formula => "none");
$csv.formula("none");
my $f = $csv.formula;
This defines the behavior of fields containing [4mformulas[24m. As
formulas are considered dangerous in spreadsheets, this attribute
can define an optional action to be taken if a field starts with an
equal sign ("=").
For purpose of code-readability, this can also be written as
my $csv = Text::CSV_XS.new(formula-handling => "none"});
$csv.formula-handling("none");
my $f = $csv.formula-handling;
or
my $csv = Text::CSV_XS.new(formula_handling => "none"});
$csv.formula_handling("none");
my $f = $csv.formula_handling;
Possible values for this attribute are
none
Take no specific action. This is the default.
$csv.formula("none");
die
Cause the process to "die" whenever a leading "=" is encountered.
$csv.formula("die");
croak
Cause the process to "die" whenever a leading "=" is encountered.
$csv.formula("croak");
This option just exists for perl5 compatibility.
diag
Report position and content of the field whenever a leading "="
is found. The value of the field is unchanged.
$csv.formula("diag");
empty
Replace the content of fields that start with a "=" with the
empty string.
$csv.formula("empty");
$csv.formula("");
undef
Replace the content of fields that start with a "=" with "Str".
$csv.formula("undef");
$csv.formula(Str);
All other values will throw an exception with error code 1500.
auto_diag
auto-diag
my $csv = Text::CSV.new(auto_diag => False);
$csv.auto_diag(True);
my $a-d = $csv.auto_diag;
Set this attribute to a number between 1 and 9 causes "error_diag"
to be automatically called in void context upon errors. The value
"True" evaluates to 1.
In case of error "2012 - EOF", this call will be void.
If "auto_diag" is set to a numeric value greater than 1, it will
"die" on errors instead of "warn".
diag_verbose
diag-verbose
my $csv = Text::CSV.new(diag_verbose => 1);
$csv.diag_verbose(2);
my $d-v = $csv.diag_verbose;
Set the verbosity of the output triggered by "auto_diag".
WIP: Does not add any information yet.
blank_is_undef
blank-is-undef
my $csv = Text::CSV.new(:blank_is_undef);
$csv.blank_is_undef(False);
my $biu = $csv.blank_is_undef;
Under normal circumstances, "CSV" data makes no distinction between
quoted- and unquoted empty fields. These both end up in an empty
string field once read, thus
1,"",," ",2
is read as
[ "1", "", "", " ", "2" ]
When [4mwriting[24m "CSV" files with "always_quote" set, the unquoted
[4mempty[24m field is the result of an undefined value. To enable this
distinction when [4mreading[24m "CSV" data, the "blank_is_undef" attribute
will cause unquoted empty fields to be set to "Str", causing the
above to be parsed as
[ "1", "", Str, " ", "2" ]
empty_is_undef
empty-is-undef
my $csv = Text::CSV.new(:empty_is_undef);
$csv.empty_is_undef(False);
my $eiu = $csv.empty_is_undef;
Going one step further than "blank_is_undef", this attribute causes
all empty fields to return as "Str", so
1,"",," ",2
is read as
[ 1, Str, Str, " ", 2 ]
Note that this effects only fields that are originally empty, not
fields that are empty after stripping allowed whitespace. YMMV.
allow_whitespace
allow-whitespace
my $csv = Text::CSV.new(:allow_whitespace);
$csv.allow_whitespace(False);
my $a-w = $csv.allow_whitespace;
When this option is set to "True", the whitespace ("TAB"'s and
"SPACE"'s) surrounding the separation sequence is removed when
parsing. If either "TAB" or "SPACE" is one of the three major
sequences "sep", "quote", or "escape" it will not be considered
whitespace.
Now lines like:
1 , "foo" , bar , 3 , zapp
are parsed as valid "CSV", even though it violates the "CSV" specs.
Note that [1mall [22mwhitespace is stripped from both start and end of
each field. That would make it [4mmore[24m than a [4mfeature[24m to enable
parsing bad "CSV" lines, as
1, 2.0, 3, ape , monkey
will now be parsed as
[ "1", "2.0", "3", "ape", "monkey" ]
even if the original line was perfectly acceptable "CSV".
allow_loose_quotes
allow-loose-quotes
my $csv = Text::CSV.new(:allow_loose_quotes);
$csv.allow_loose_quotes(False);
my $alq = $csv.allow_loose_quotes;
By default, parsing unquoted fields containing "quote"'s like
1,foo "bar" baz,42
would result in parse error 2034. Though it is still bad practice
to allow this format, we cannot help the fact that some vendors
make their applications spit out lines styled this way.
If there is [1mreally [22mbad "CSV" data, like
1,"foo "bar" baz",42
or
1,""foo bar baz"",42
there is a way to get this data-line parsed and leave the quotes
inside the quoted field as-is. This can be achieved by setting
"allow_loose_quotes" [1mAND [22mmaking sure that the "escape" is [4mnot[24m equal
to "quote".
allow_loose_escapes
allow-loose-escapes
my $csv = Text::CSV.new(:allow_loose_escapes);
$csv.allow_loose_escapes(False);
my $ale = $csv.allow_loose_escapes;
Parsing fields that have "escape" sequences that escape characters
that do not need to be escaped, like:
my $csv = Text::CSV.new(escape_char => "\\");
$csv.parse(q{1,"my bar\'s",baz,42});
would result in parse returning "False" with reason 2025. Though it
is bad practice to allow this format, this attribute enables you to
treat all escape sequences equal.
allow_unquoted_escape
allow-unquoted-escape
my $csv = Text::CSV.new(:allow_unquoted_escape);
$csv.allow_unquoted_escape(False);
my $aue = $csv.allow_unquoted_escape;
A backward compatibility issue where "escape" differs from "quote"
prevents "escape" to be in the first position of a field. If
"quote" is equal to the default """ and "escape" is set to "\",
this would be illegal:
1,\0,2
Setting this attribute to "True" might help to overcome issues with
backward compatibility and allow this style.
always_quote
always-quote
my $csv = Text::CSV.new(:always_quote);
$csv.always_quote(False);
my $f = $csv.always_quote;
By default the generated fields are quoted only if they [4mneed[24m to be.
For example, if they contain the separator sequence. If you set
this attribute to 1 then [4mall[24m defined fields will be quoted.
(undefined ("Str") fields are not quoted, see "blank_is_undef").
This makes it quite often easier to handle exported data in
external applications. (Poor creatures who are better to use
Text::CSV. :)
quote_empty
quote-empty
my $csv = Text::CSV.new(:quote_empty);
$csv.quote_empty(False);
my $q-s = $csv.quote_empty;
By default the generated fields are quoted only if they [4mneed[24m to be.
An empty defined field does not need quotation. If you set this
attribute to "True" then empty defined fields will be quoted. See
also "always_quote".
quote_space
quote-space
my $csv = Text::CSV.new(:quote_space);
$csv.quote_space(False);
my $q-s = $csv.quote_space;
By default, a space in a field would trigger quotation. As no rule
exists this to be forced in "CSV", nor any for the opposite, the
default is "True" for safety. You can exclude the space from this
trigger by setting this attribute to "False".
escape_null
quote-null
my $csv = Text::CSV.new(:escape_null);
$csv.escape_null(False);
my $q-n = $csv.escape_null;
By default, a "NULL" byte in a field would be escaped. This option
enables you to treat the "NULL" byte as a simple binary character
in binary mode (the "binary => True" is set). The default is
"True". You can prevent "NULL" escapes by setting this attribute to
"False".
quote_binary
quote-binary
my $csv = Text::CSV.new(:quote_binary);
$csv.quote_binary(False);
my $q-b = $csv.quote_binary;
By default, all "unsafe" bytes inside a string cause the combined
field to be quoted. By setting this attribute to "False", you can
disable that trigger for bytes >= 0x7F. (WIP)
keep_meta
keep-meta
my $csv = Text::CSV.new(:keep_meta);
$csv.keep_meta(False);
my $k-m = $csv.keep_meta_info;
By default, the parsing of input records is as simple and fast as
possible. However, some parsing information - like quotation of
the original field - is lost in that process. Setting this flag to
true enables retrieving that information after parsing with the
methods "meta_info", "is_quoted", and "is_binary" described below.
Default is "False" for ease of use.
If "keep-meta" is set to "True", the returned fields are not of
type "Str" but of type "CSV::Field".
undef_str
undef-str
NYI - this should replace undefined values in generating CSV
comment_str
comment-str
my $csv = Text::CSV.new(comment_str => "#");
$csv.comment_str (Str);
my $s = $csv.comment_str;
This attribute optionally defines a string to be recognized as
comment. If this attribute is defined, all lines starting with this
sequence will not be parsed as CSV but skipped as comment.
This attribute has no meaning when generating CSV.
types
NYI
A set of column types; the attribute is immediately passed to the
"types" method.
callbacks
See the "Callbacks" section below.
To sum it up,
$csv = Text::CSV.new;
is equivalent to
$csv = Text::CSV.new(
eol => Nil, # \r, \n, or \r\n
sep => ',',
quote => '"',
escape => '"',
binary => True,
auto-diag => False,
diag-verbose => 0,
blank-is-undef => False,
empty-is-undef => False,
allow-whitespace => False,
allow-loose-quotes => False,
allow-loose-escapes => False,
allow-unquoted-escape => False,
always-quote => False,
quote-space => True,
escape-null => True,
quote-binary => True,
keep-meta => False,
strict => False,
formula => "none",
undef-str => Str,
comment-str => Str,
types => Nil,
callbacks => Nil,
});
For all of the above mentioned flags, an accessor method is available
where you can inquire the current value, or change the value
my $quote = $csv.quote;
$csv.binary(True);
It is not wise to change these settings halfway through writing "CSV"
data to a stream. If however you want to create a new stream using the
available "CSV" object, there is no harm in changing them.
If the "new" constructor call fails, an exception of type "CSV::Diac"
is thrown with the reason like the "error_diag" method would return:
my $e;
{ $csv = Text::CSV.new(ecs_char => ":") or
CATCH { default { $e = $_; }}
}
$e and $e.message.say;
The message will be a string like
"INI - Unknown attribute 'ecs_char'"
[1mprint[0m
$status = $csv.print($io, $fld, ... );
$status = $csv.print($io, ($fld, ...));
$status = $csv.print($io, [$fld, ...]);
$status = $csv.print($io, @fld );
$csv.column_names(%fld.keys); # or use a subset
$status = $csv.print($io, %fld );
Similar to "combine" + "string" + "print", but much more efficient. It
takes an IO object and any number of arguments interpreted as fields.
The resulting string is immediately written to the $io stream.
NYI: no fields in combination with "bind_columns", like
$csv.bind_columns(\($foo, $bar));
$status = $csv.print($fh);
A benchmark showed this order of preference, but the difference is
within noise range:
my @data = ^20;
$csv.print($io, @data ); # 2.6 sec
$csv.print($io, [ @data ]); # 2.7 sec
$csv.print($io, ^20 ); # 2.7 sec
$csv.print($io, \@data ); # 2.8 sec
[1msay[0m
Is the same a s"print" where "eol" defaults to "$*OUT.nl".
$status = $csv.say($io, $fld, ... );
$status = $csv.say($io, ($fld, ...));
$status = $csv.say($io, [$fld, ...]);
$status = $csv.say($io, @fld );
$csv.column_names(%fld.keys); # or use a subset
$status = $csv.say($io, %fld );
[1mcombine[0m
$status = $csv.combine(@fields);
$status = $csv.combine($fld, ...);
$status = $csv.combine(\@fields);
This method constructs a "CSV" row from @fields, returning success or
failure. Failure can result from lack of arguments or an argument that
contains invalid data. Upon success, "string" can be called to retrieve
the resultant "CSV" string. Upon failure, the value returned by
"string" is undefined and "error_input" could be called to retrieve the
invalid argument. (WIP)
[1mstring[0m
$line = $csv.string;
This method returns the input to "parse" or the resultant "CSV" string
of "combine", whichever was called more recently. If "eol" is defined,
it is added to the string.
[1mgetline[0m
@row = $csv.getline($io);
@row = $csv.getline($io, :meta);
@row = $csv.getline($str);
@row = $csv.getline($str, :meta);
This is the counterpart to "print", as "parse" is the counterpart to
"combine": it parses a row from the $io handle or $str using the
"getline" method associated with $io (or the internal temporary IO
handle used to read from the string as if it were an IO handle) and
parses this row into an array. This array is returned by the function
or "Array" for failure. When $io does not support "getline", you are
likely to hit errors.
NYI: When fields are bound with "bind_columns" the return value is a
reference to an empty list.
[1mgetline_all =head2 getline-all[0m
@rows = $csv.getline_all($io);
@rows = $csv.getline_all($io, :meta);
@rows = $csv.getline_all($io, $offset);
@rows = $csv.getline_all($io, $offset, :meta);
@rows = $csv.getline_all($io, $offset, $length);
@rows = $csv.getline_all($io, $offset, $length, :meta);
This will return a list of getline($io) results. If $offset is
negative, as with "splice", only the last "abs($offset)" records of $io
are taken into consideration.
Given a CSV file with 10 lines:
lines call
----- ---------------------------------------------------------
0..9 $csv.getline_all($io) # all
0..9 $csv.getline_all($io, 0) # all
8..9 $csv.getline_all($io, 8) # start at 8
- $csv.getline_all($io, 0, 0) # start at 0 first 0 rows
0..4 $csv.getline_all($io, 0, 5) # start at 0 first 5 rows
4..5 $csv.getline_all($io, 4, 2) # start at 4 first 2 rows
8..9 $csv.getline_all($io, -2) # last 2 rows
6..7 $csv.getline_all($io, -4, 2) # first 2 of last 4 rows
[1mgetline_hr =head2 getline-hr[0m
The "getline_hr" and "column_names" methods work together to allow you
to have rows returned as hashes instead of arrays. You must invoke
"column_names" first to declare your column names.
$csv.column_names(< code name price description >);
%hr = $csv.getline_hr($str, :meta);
%hr = $csv.getline_hr($io);
say "Price for %hr<name> is %hr<price> \c[EURO SIGN]";
"getline_hr" will fail if invoked before "column_names".
[1mgetline_hr_all =head2 getline-hr-all[0m
@rows = $csv.getline_hr_all($io);
@rows = $csv.getline_hr_all($io, :meta);
@rows = $csv.getline_hr_all($io, $offset);
@rows = $csv.getline_hr_all($io, $offset, :meta);
@rows = $csv.getline_hr_all($io, $offset, $length);
@rows = $csv.getline_hr_all($io, $offset, $length, :meta);
This will return a list of getline_hr($io) results.
[1mparse[0m
$status = $csv.parse($line);
This method decomposes a "CSV" string into fields, returning success or
failure. Failure can result from a lack of argument or improper format
in the given "CSV" string. Upon success, invoke "fields" or "strings"
to get the decomposed fields. Upon failure these methods shall not be
trusted to return reliable data.
NYI: You may use the "types" method for setting column types. See
"types"' description below.
[1mfragment[0m
This function implements RFC7111
<https://datatracker.ietf.org/doc/html/rfc7111> (URI Fragment
Identifiers for the text/csv Media Type).
my @rows = $csv.fragment($io, $spec);
In specifications, "*" is used to specify the [4mlast[24m item, a dash ("-")
to indicate a range. All indices are 1-based: the first row or column
has index 1. Selections can be combined with the semi-colon (";").
When using this method in combination with "column_names", the returned
array will be a list of hashes instead of an array of arrays. A
disjointed cell-based combined selection might return rows with
different number of columns making the use of hashes unpredictable.
$csv.column_names(< Name Age >);
my @rows = $csv.fragment($io, "row=3;8");
Note that for "col=".."", the column names are the names for [4mbefore[24m the
selection is taken to make it more consistent with reading possible
headers from the first line of the CSV datastream.
$csv,column_names(< foo bar >); # WRONG
$csv.fragment($io, "col=3");
would set the column names for the first two columns that are then
skipped in the fragment. To skip the unwanted columns, use
placeholders.
$csv.column_names(< x x Name >);
$csv.fragment($io, "col=3");
WIP: If the "after_parse" callback is active, it is also called on
every line parsed and skipped before the fragment.
row
row=4
row=5-7
row=6-*
row=1-2;4;6-*
col
col=2
col=1-3
col=4-*
col=1-2;4;7-*
cell
In cell-based selection, the comma (",") is used to pair row and
column
cell=4,1
The range operator ("-") using "cell"s can be used to define top-left
and bottom-right "cell" location
cell=3,1-4,6
The "*" is only allowed in the second part of a pair
cell=3,2-*,2 # row 3 till end, only column 2
cell=3,2-3,* # column 2 till end, only row 3
cell=3,2-*,* # strip row 1 and 2, and column 1
Cells and cell ranges may be combined with ";", possibly resulting in
rows with different number of columns
cell=1,1-2,2;3,3-4,4;1,4;4,1
Disjointed selections will only return selected cells. The cells that
are not specified will not be included in the returned set, not even
as "Str". As an example given a "CSV" like
11,12,13,...19
21,22,...28,29
: :
91,...97,98,99
with "cell=1,1-2,2;3,3-4,4;1,4;4,1" will return:
11,12,14
21,22
33,34
41,43,44
Overlapping cell-specs will return those cells only once, So
"cell=1,1-3,3;2,2-4,4;2,3;4,2" will return:
11,12,13
21,22,23,24
31,32,33,34
42,43,44
RFC7111 <https://datatracker.ietf.org/doc/html/rfc7111> does [1mnot [22mallow
different types of specs to be combined (either "row" [4mor[24m "col" [4mor[0m
"cell"). Passing an invalid fragment specification will croak and set
error 2013.
Using "colrange" and "rowrange" instead of "fragment" will allow you to
combine row- and column selecting as a grid.
[1mcolrange[0m
my Int @range = ^5, 5..9;
$csv.colrange(@range);
$csv.colrange("0-4;6-10");
my @range = $csv.colrange;
Set or inspect the column ranges. When passed as an array of "Int", the
indexes are 0-based. When passed as a string, the syntax of the range
is as defined by RFC7111 and thus 1-based.
[1mrowrange[0m
$csv.rowrange("1;16-*");
my @r = $csv.rowrange;
Set or inspect the row ranges. Only supports RFC7111 style. Indexes
are 1-based.
[1mcolumn_names =head2 column-names[0m
Set the "keys" that will be used in the "getline_hr" calls. If no keys
(column names) are passed, it will return the current setting as a
list.
$csv.column_names(< code description price >);
my @names = $csv.column_names;
"column_names" accepts a list of strings (the column names) or a single
array with the names. You can pass the return value from "getline" too:
$csv.column_names($csv.getline($io));
"column_names" does [1mno [22mchecking on duplicates at all, which might lead
to unexpected results. As raku does not accept undefined keys in a
hash, passing just types will lead to fail later on.
$csv.column_names(Str, "", "name"); # Will FAIL becaus of Str
$csv.column_names(< code name count name >); # will drop the second column
%hr = $csv.getline_hr($io);
[1mheader[0m
Parse the CSV header and set "sep" and encoding.
my @hdr = $csv.header($fh).column-names;
$csv.header($fh, sep-set => [ ";", ",", "|", "\t" ]);
$csv.header($fh, munge-column-names => "fc");
The first argument should be a file handle.
Assuming that the file opened for parsing has a header, and the header
does not contain problematic characters like embedded newlines, read
the first line from the open handle then auto-detect whether the header
separates the column names with a character from the allowed separator
list.
If any of the allowed separators matches, and none of the [4mother[24m allowed
separators match, set "sep" to that separator for the current CSV_XS
instance and use it to parse the first line, map those to lowercase,
and use that to set the instance "column_names":
my $csv = Text::CSV.new;
my $fh = open "file.csv";
$csv.header($fh);
while (my $row = $csv.getline_hr($fh)) {
...
}
If the header is empty, contains more than one unique separator out of
the allowed set, contains empty fields, or contains identical fields
(after folding), it will croak with error 1010, 1011, 1012, or 1013
respectively.
If the header contains embedded newlines or is not valid CSV in any
other way, this method will throw an exception.
A successful call to "header" will always set the "sep" of the $csv
object. This behavior can not be disabled.
[4mreturn[24m [4mvalue[0m
On error this method will throw an exception.
On success, this method will return the instance.
[4mOptions[0m
sep-set
$csv.header($fh, sep_set => [ ";", ",", "|", "\t" ]);
The list of legal separators defaults to "[ ";", "," ]" and can be
changed by this option.
Multi-byte sequences are allowed, both multi-character and Unicode.
See "sep".
munge-column-names
This option offers the means to modify the column names into
something that is most useful to the application. The default is to
map all column names to fold case.
$csv.header($fh, munge-column-names => "lc");
The following values are available:
fc - fold case
lc - lower case
uc - upper case
none - do not change
&cb - supply a callback
$csv.header($fh, munge-column-names => { "column_".$col++ });
set-column-names
$csv.header($fh, :set-column-names);
The default is to set the instances column names using "column_names"
if the method is successful, so subsequent calls to "getline_hr" can
return a hash. Disable setting the header can be forced using a false
value for this option like ":!set-column-names".
[1mbind_columns =head2 bind-columns[0m
NYI!
Takes a list of scalar references to be used for output with "print" or
to store in the fields fetched by "getline". When you do not pass
enough references to store the fetched fields in, "getline" will fail
with error 3006. If you pass more than there are fields to return, the
content of the remaining references is left untouched.
$csv.bind_columns(\$code, \$name, \$price, \$description);
while ($csv.getline($io)) {
print "The price of a $name is \x[20ac] $price\n";
}
To reset or clear all column binding, call "bind_columns" with the
single undefined argument like "Array". This will also clear column
names.