-
Notifications
You must be signed in to change notification settings - Fork 11
/
CSV.pod6
2846 lines (1934 loc) · 72.9 KB
/
CSV.pod6
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
=encoding utf-8
=head1 DISCLAIMER
Note that updating these docs is an ongoing process and some perl5 idioms
might not have been translated yet into correct perl6 idiom. My bad. Sorry.
(Feedback welcome)
=head1 NAME
Text::CSV - comma-separated values manipulation routines
=head1 SYNOPSIS
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 => False;
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;
=head1 DESCRIPTION
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 C<CSV> string and parse a C<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, C<WIP> stands for "Work In Progress" and
C<NYI> for "Not Yet Implemented". The goal is to get rid of all of those.
=head2 Embedded newlines
B<Important Note>: 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
L</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 C<chomp>
lines, which will also remove the newline sequence if that sequence is not
(part of) the newline at all. As the C<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 B<not> pass L<C<eol>|/eol> in the parser (it accepts
C<\n>, C<\r>, B<and> C<\r\n> by default) and then
my $csv = Text::CSV.new;
my $io = open $file, :r, chomp => False;
while (my $row = $csv.getline($io)) {
my @fields = @$row;
}
=head2 Binary data
For now, Text::CSV only accepts Unicode. Binary data is planned.
=head1 SPECIFICATION
While no formal specification for CSV exists, RFC 4180 I<1>) describes the
common format and establishes C<text/csv> as the MIME type registered with
the IANA. RFC 7111 I<2> adds fragments to CSV.
Many informal documents exist that describe the C<CSV> format. "How To: The
Comma Separated Value (CSV) File Format" I<3>) provides an overview of the
C<CSV> format in the most widely used applications and explains how it can
best be used and supported.
1) http://tools.ietf.org/html/rfc4180
2) http://tools.ietf.org/html/rfc7111
3) http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm
The basic rules are as follows:
B<CSV> is 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 C<CSV> file format does not require a specific
character encoding, byte order, or line terminator format.
=over 2
=item *
Each record is a single line ended by a line feed (ASCII/C<LF>=C<0x0A>) or
a carriage return and line feed pair (ASCII/C<CRLF>=C<0x0D 0x0A>), however,
line-breaks may be embedded.
=item *
Fields are separated by commas.
=item *
Allowable characters within a C<CSV> field include C<0x09> (C<TAB>) and the
inclusive range of C<0x20> (space) through C<0x7E> (tilde). In binary mode
all characters are accepted, at least in quoted fields.
=item *
A field within C<CSV> must be surrounded by double-quotes to contain a
separator character (comma).
=back
Though this is the most clear and restrictive definition, Text::CSV is way
more liberal than this, and allows extension:
=over 2
=item *
Line termination by a single carriage return is accepted by default
=item *
The separation, escape, and escape can be any valid Unicode sequence.
=item *
A field in C<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 C<"0> for representation of a NULL
byte. Using C<0x00> is just as valid.
=item *
Several violations of the above specification may be lifted by passing some
options as attributes to the object constructor.
=back
=head1 METHODS
=head2 version
X<version>
Returns the current module version.
=head2 new
X<new>
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:
=over 4
=item eol
X<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 L</print> or the record separator
for L</getline>.
When not set in a B<parser> instance, the default behavior is to accept
C<\n>, C<\r>, and C<\r\n>, so it is probably safer to not specify C<eol> at
all. Passing C<Str> or the empty string behave the same.
As perl6 interprets C<\r\n> as a single grapheme in input, it is dissuaded
to use C<\r\n> as C<eol> when parsing. Please choose C<Str> instead.
When not passed in a B<generating> instance, records are not terminated at
all, so it is probably wise to pass something you expect. A safe choice for
C<eol> on output is either C<\n> or C<\r\n>.
Common values for C<eol> are C<"\012"> (C<\n> or Line Feed), C<"\015\012">
(C<\r\n> or Carriage Return, Line Feed), and C<"\015"> (C<\r> or Carriage
Return).
=item sep
X<sep>
=item sep_char
X<sep_char>
=item sep-char
X<sep-char>
=item separator
X<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: (C<,>). 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 L</CAVEATS>
=item quote
X<quote>
=item quote_char
X<quote_char>
=item quote-char
X<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 (C<">). A value of C<Str> disables quotation
(for simple cases only).
The quotation sequence can not be equal to the separation sequence or the
newline sequence.
See also L</CAVEATS>
=item escape
X<escape>
=item escape_char
X<escape_char>
=item escape-char
X<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 C<escape> defaults to being the double-quote mark (C<">). In other
words the same as the default sequence for L<C<quote>|/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 L<C<quote>|/quote> without changing C<escape>, C<escape> will
still be the double-quote (C<">). If instead you want to escape
L<C<quote>|/quote> by doubling it you will need to also change C<escape> to
be the same as what you have changed L<C<quote>|/quote> to.
The escape sequence can not be equal to the separation sequence.
=item binary
X<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 C<True>, you may use binary data in quoted fields,
including line feeds, carriage returns and C<NULL> bytes. (The latter could
be escaped as C<"0>.) By default this feature is on.
Note that valid Unicode (UTF-8) is not considered binary.
=item auto_diag
X<auto_diag>
=item auto-diag
X<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 C<1> and C<9> causes L</error_diag>
to be automatically called in void context upon errors. The value C<True>
evaluates to C<1>.
In case of error C<2012 - EOF>, this call will be void.
If C<auto_diag> is set to a numeric value greater than C<1>, it will C<die>
on errors instead of C<warn>.
=item diag_verbose
X<diag_verbose>
=item diag-verbose
X<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 C<auto_diag>.
WIP: Does not add any information yet.
=item blank_is_undef
X<blank_is_undef>
=item blank-is-undef
X<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, C<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 I<writing> C<CSV> files with L<C<always_quote>|/always_quote> set, the
unquoted I<empty> field is the result of an undefined value. To enable this
distinction when I<reading> C<CSV> data, the C<blank_is_undef> attribute
will cause unquoted empty fields to be set to C<Str>, causing the above
to be parsed as
[ "1", "", Str, " ", "2" ]
=item empty_is_undef
X<empty_is_undef>
=item empty-is-undef
X<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 L<C<blank_is_undef>|/blank_is_undef>, this
attribute causes all empty fields to return as C<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.
=item allow_whitespace
X<allow_whitespace>
=item allow-whitespace
X<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 C<True>, the whitespace (C<TAB>'s and C<SPACE>'s)
surrounding the separation sequence is removed when parsing. If either
C<TAB> or C<SPACE> is one of the three major sequences L<C<sep>|/sep>,
L<C<quote>|/quote>, or L<C<escape>|/escape> it will not be considered
whitespace.
Now lines like:
1 , "foo" , bar , 3 , zapp
are parsed as valid C<CSV>, even though it violates the C<CSV> specs.
Note that B<all> whitespace is stripped from both start and end of each
field. That would make it I<more> than a I<feature> to enable parsing bad
C<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 C<CSV>.
=item allow_loose_quotes
X<allow_loose_quotes>
=item allow-loose-quotes
X<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 L<C<quote>|/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 B<really> bad C<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 C<allow_loose_quotes>
B<AND> making sure that the L<C<escape>|/escape> is I<not> equal to
L<C<quote>|/quote>.
=item allow_loose_escapes
X<allow_loose_escapes>
=item allow-loose-escapes
X<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 L<C<escape>|/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 C<False> with reason 2025. Though it is bad
practice to allow this format, this attribute enables you to treat all
escape sequences equal.
=item allow_unquoted_escape
X<allow_unquoted_escape>
=item allow-unquoted-escape
X<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 L<C<escape>|/escape> differs from
L<C<quote>|/quote> prevents L<C<escape>|/escape> to be in the first
position of a field. If L<C<quote>|/quote> is equal to the default C<"> and
L<C<escape>|/escape> is set to C<\>, this would be illegal:
1,\0,2
Setting this attribute to C<True> might help to overcome issues with
backward compatibility and allow this style.
=item always_quote
X<always_quote>
=item always-quote
X<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 I<need> to be. For
example, if they contain the separator sequence. If you set this attribute
to C<1> then I<all> defined fields will be quoted. (undefined (C<Str>)
fields are not quoted, see L</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. :)
=item quote_empty
X<quote_empty>
=item quote-empty
X<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 I<need> to be. An
empty defined field does not need quotation. If you set this attribute to
C<True> then empty defined fields will be quoted. See also
L<C<always_quote>|/always_quote>.
=item quote_space
X<quote_space>
=item quote-space
X<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 C<CSV>, nor any for the opposite, the default is
C<True> for safety. You can exclude the space from this trigger by setting
this attribute to C<False>.
=item quote_null
X<quote_null>
=item quote-null
X<quote-null>
my $csv = Text::CSV.new(:quote_null);
$csv.quote_null(False);
my $q-n = $csv.quote_null;
By default, a C<NULL> byte in a field would be escaped. This option enables
you to treat the C<NULL> byte as a simple binary character in binary mode
(the C<< binary => True >> is set). The default is C<True>. You can prevent
C<NULL> escapes by setting this attribute to C<False>.
=item quote_binary
X<quote_binary>
=item quote-binary
X<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 C<False>, you can disable that
trigger for bytes >= C<0x7F>. (WIP)
=item keep_meta
X<keep_meta>
=item keep-meta
X<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 L</meta_info>, L</is_quoted>,
and L</is_binary> described below. Default is C<False> for ease of use.
If C<keep-meta> is set to C<True>, the returned fields are not of type
C<Str> but of type L<C<CSV::Field>|/CSV::Field>.
=item types
NYI
A set of column types; the attribute is immediately passed to the L</types>
method.
=item callbacks
X<callbacks>
See the L</Callbacks> section below.
=back
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,
quote_null => True,
quote_binary => True,
keep_meta => False,
verbatim => False,
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 C<CSV> data
to a stream. If however you want to create a new stream using the available
C<CSV> object, there is no harm in changing them.
If the L</new> constructor call fails, an exception of type C<CSV::Diac> is
thrown with the reason like the L</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'"
=head2 print
X<print>
$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 L</combine> + L</string> + L</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 C<$io> stream.
NYI: no fields in combination with L</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
=head2 say
X<say>
Is the same a sL</print> where L<C<eol>|/eol> defaults to C<$*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 );
=head2 combine
X<combine>
$status = $csv.combine(@fields);
$status = $csv.combine($fld, ...);
$status = $csv.combine(\@fields);
This method constructs a C<CSV> row from C<@fields>, returning success or
failure. Failure can result from lack of arguments or an argument that
contains invalid data. Upon success, L</string> can be called to retrieve
the resultant C<CSV> string. Upon failure, the value returned by L</string>
is undefined and L</error_input> could be called to retrieve the invalid
argument. (WIP)
=head2 string
X<string>
$line = $csv.string;
This method returns the input to L</parse> or the resultant C<CSV> string
of L</combine>, whichever was called more recently. If L<C<eol>|/eol> is
defined, it is added to the string.
=head2 getline
X<getline>
@row = $csv.getline($io);
@row = $csv.getline($io, :meta);
@row = $csv.getline($str);
@row = $csv.getline($str, :meta);
This is the counterpart to L</print>, as L</parse> is the counterpart to
L</combine>: it parses a row from the C<$io> handle or C<$str> using the
L</getline> method associated with C<$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 C<Array>
for failure. When C<$io> does not support C<getline>, you are likely to hit
errors.
NYI: When fields are bound with L</bind_columns> the return value is a
reference to an empty list.
=head2 getline_all
=head2 getline-all
X<getline_all>
X<getline-all>
@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 L<getline($io)|/getline> results.
If C<$offset> is negative, as with C<splice>, only the last C<abs($offset)>
records of C<$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
=head2 getline_hr
=head2 getline-hr
X<getline_hr>
X<getline-hr>
The L</getline_hr> and L</column_names> methods work together to allow you
to have rows returned as hashes instead of arrays. You must invoke
L</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]";
L</getline_hr> will fail if invoked before L</column_names>.
=head2 getline_hr_all
=head2 getline-hr-all
X<getline_hr_all>
X<getline-hr-all>
@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 L<getline_hr($io)|/getline_hr> results.
=head2 parse
X<parse>
$status = $csv.parse($line);
This method decomposes a C<CSV> string into fields, returning success or
failure. Failure can result from a lack of argument or improper format in
the given C<CSV> string. Upon success, invoke L</fields> or L</strings> to
get the decomposed fields. Upon failure these methods shall not be trusted
to return reliable data.
NYI: You may use the L</types> method for setting column types. See
L</types>' description below.
=head2 fragment
X<fragment>
This function implements L<RFC7111|http://tools.ietf.org/html/rfc7111>
(URI Fragment Identifiers for the text/csv Media Type).
my @rows = $csv.fragment($io, $spec);
In specifications, C<*> is used to specify the I<last> item, a dash (C<->)
to indicate a range. All indices are C<1>-based: the first row or column
has index C<1>. Selections can be combined with the semi-colon (C<;>).
When using this method in combination with L</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 C<col="..">, the column names are the names for I<before> 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 L</after_parse> callback is active, it is also called on every
line parsed and skipped before the fragment.
=over 2
=item row
row=4
row=5-7
row=6-*
row=1-2;4;6-*
=item col
col=2
col=1-3
col=4-*
col=1-2;4;7-*
=item cell
In cell-based selection, the comma (C<,>) is used to pair row and column
cell=4,1
The range operator (C<->) using C<cell>s can be used to define top-left and
bottom-right C<cell> location
cell=3,1-4,6
The C<*> 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 C<;>, 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
C<Str>. As an example given a C<CSV> like
11,12,13,...19
21,22,...28,29
: :
91,...97,98,99
with C<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
C<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
=back
L<RFC7111|http://tools.ietf.org/html/rfc7111> does B<not> allow different
types of specs to be combined (either C<row> I<or> C<col> I<or> C<cell>).
Passing an invalid fragment specification will croak and set error 2013.
Using L</colrange> and L</rowrange> instead of L</fragment> will allow you
to combine row- and column selecting as a grid.
=head2 colrange
X<colrange>
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 C<Int>, the
indexes are 0-based. When passed as a string, the syntax of the range is as
defined by L<RFC7111|/fragment> and thus 1-based.
=head2 rowrange
X<rowrange>
$csv.rowrange("1;16-*");
my @r = $csv.rowrange;
Set or inspect the row ranges. Only supports L<RFC7111|/fragment> style.
Indexes are 1-based.
=head2 column_names
=head2 column-names
X<column_names>
X<column-names>
Set the "keys" that will be used in the L</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;
L</column_names> accepts a list of strings (the column names) or a single
array with the names. You can pass the return value from L</getline> too:
$csv.column_names($csv.getline($io));
L</column_names> does B<no> checking on duplicates at all, which might lead
to unexpected results. As perl6 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);
=head2 header
Parse the CSV header and set C<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 I<other> allowed
separators match, set L<C<sep>|/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 L</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 C<header> will always set the L<C<sep>|/sep> of the
C<$csv> object. This behavior can not be disabled.
=head3 return value
On error this method will throw an exception.
On success, this method will return the instance.
=head3 Options