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

#!/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,

     });

你可能感兴趣的:(text)