問題描述
Perl Text::CSV_XS 從字符串中讀取 (Perl Text::CSV_XS read from string)
How to I use the Text::CSV_XS module to read its input from a CSV string. Then only information I can find documented is reading from a file.
Would the fastest way to do it be splitting up the CSV string using the perl split function and reading each line from there or is there some built in method with Text::CSV_XS to read directly from a CSV string?
Thanks
‑‑‑‑‑
參考解法
方法 1:
The getline
method of Text::CSV_XS
will read from a file handle, so you can open the scalar string as a stream and pass that file handle.
This program demonstrates
use strict;
use warnings;
use Text::CSV_XS;
my $string = <<'END';
a,b,c,d
e,f,g,h
i,j,k,l
m,n,o,p
END
my $csv = Text::CSV_XS‑>new;
open my $fh, '<', \$string;
while (my $row = $csv‑>getline($fh)) {
print join('‑', @$row), "\n";
}
output
a‑b‑c‑d
e‑f‑g‑h
i‑j‑k‑l
m‑n‑o‑p
方法 2:
Use the parse method;
#!/usr/bin/env perl
#
use strict;
use warnings;
use Data::Dumper;
use Text::CSV_XS;
my $csv = Text::CSV_XS‑>new();
if ( $csv‑>parse('Column1,Column2,Column2') ) {
my @columns = $csv‑>fields;
print Dumper( \@columns );
}
else {
# Failed to parse the CSV data
}