2011年09月11日 23:56
my @fields = split /,/, $line; # NG! セル内にコンマがあると使えない
my @fields = split /\t/, $line; # NG! 一般的にセル内にタブは使わない(?)
Text::CSV (あればXS、なければPPを使う)
Text::CSV_PP (Pure Perl)
Text::CSV_XS (高速)
Text::CSV::Simple
$ sudo cpan Text::CSV Text::CSV_XS Text::CSV::Simple
Embedded newlines
Unicode (UTF8)
FUNCTIONS
DIAGNOSTICS
use Text::CSV;
my @rows;
open my $fh, "<:encoding(utf8)", "test.csv" or die "test.csv: $!";
while ( my $row = $csv->getline( $fh ) ) {
$row->[2] =~ m/pattern/ or next; # 3rd field should match
push @rows, $row;
}
$csv->eof or $csv->error_diag();
close $fh;
$csv->eol ("\r\n");
open $fh, ">:encoding(utf8)", "new.csv" or die "new.csv: $!";
$csv->print ($fh, $_) for @rows;
close $fh or die "new.csv: $!";
my $csv = Text::CSV->new ({ binary => 1, eol => $/ });
while (<>) { # これだと、改行を含むセルが崩れる。
$csv->parse ($_);
my @fields = $csv->fields ();
my $csv = Text::CSV->new ({ binary => 1, eol => $/ });
while (my $row = $csv->getline (*ARGV)) {
my @fields = @$row;
my $csv = Text::CSV->new ({ binary => 1, eol => $/ });
open my $io, "<", $file or die "$file: $!";
while (my $row = $csv->getline ($io)) {
my @fields = @$row;
$csv->types ([Text::CSV::IV (), # integer
Text::CSV::NV (), # numeric/float
Text::CSV::PV ()]); # string
$csv->types (undef); # リセット
$types = $csv->types (); # 現在の設定を取得
# IV Set field type to integer.
# NV Set field type to numeric/float.
# PV Set field type to string.