您的位置:首页 > 其它

用Text::CSV_XS模块处理csv文件

2013-04-08 08:21 197 查看
#!/usr/bin/perl
# 测试csv 文件
# 需求:
# 从csv 文件中抽取id,song_title,ARTIST_NAME,LRC_TEXT
#------------------------模块定义------------------------
use 5.014;                       #自动打开 strict
use utf8;                        #打开源代码的 utf8 flag
use FindBin qw($Bin);            #当前目录
use Text::CSV::Encoded;          #csv 解析
#--------------------解析csv 文件-------------------------
my @rows;
my $csv = Text::CSV::Encoded->new ({
encoding_in  => "gb2312", # the encoding comes into   Perl
encoding_out => "gb2312", # the encoding comes out of Perl
});

#$csv = Text::CSV::Encoded->new ({ encoding  => "utf8" });

open my $fh, "<", "$Bin/res/song.csv" or die "song.csv: $!";

while ( my $row = $csv->getline($fh) ) {

my @lines = @{$row}[0,1,7,3];
push @rows, \@lines;

}
$csv->eof or $csv->error_diag();
close $fh;

$csv->eol("\r\n");
$csv->quote_char('"');
$csv->always_quote(1);
open $fh, ">", "$Bin/res/new.csv" or die "new.csv: $!";
$csv->print( $fh, $_ ) for @rows;
close $fh or die "new.csv: $!";


默认的设置

$csv = Text::CSV_XS->new ({
quote_char            => '"',
escape_char           => '"',
sep_char              => ',',
eol                   => $\,
always_quote          => 0,
quote_space           => 1,
quote_null            => 1,
quote_binary          => 1,
binary                => 0,
keep_meta_info        => 0,
allow_loose_quotes    => 0,
allow_loose_escapes   => 0,
allow_unquoted_escape => 0,
allow_whitespace      => 0,
blank_is_undef        => 0,
empty_is_undef        => 0,
verbatim              => 0,
auto_diag             => 0,
diag_verbose          => 0,
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: