2010-01-12 26 views
3

我有一個表中有一些Unicode。我知道Unicode數據很好,因爲它在我們的Web服務器上以JSON出現就好。但由於某種原因,我所生成的CSV結果被打亂了。這是我們目前的代碼:如何在Perl 5中將此Unicode表導出爲CSV?

my $csv = Text::CSV->new ({ eol => "\015\012" }); 
    open my $fh, '>:encoding(utf8)', 'Foo.csv'; 
    my $sth = $dbh->prepare("SELECT * FROM Foo"); 
    $sth->execute(); 
    my $i = 0; 
    while (my $row = $sth->fetchrow_hashref) { 
    $csv->print($fh, [keys %$row]) if $i == 0; 
    $csv->print($fh, [values %$row]); 
    $i++; 
    } 

任何想法?

+0

這將幫助,如果你向我們展示了預期和錯位輸出。 :) – 2010-01-13 14:26:51

回答

3

除了編碼問題,我不認爲values將始終以相同的順序給字段保證。每次調用它時,您可能會從fetchrow_hashref獲取不同的哈希參數。解決方案是使用fetchrow_arrayref

Text::CSV建議Text::CSV::Encoded

my $csv = Text::CSV::Encoded->new({ eol => "\015\012" }); 
open my $fh, '>:raw', 'Foo.csv'; 
my $sth = $dbh->prepare("SELECT * FROM Foo"); 
$sth->execute(); 
$csv->print($fh, $sth->{NAME_lc}); # or NAME or NAME_uc 

while (my $row = $sth->fetchrow_arrayref) { 
    $csv->print($fh, $row); 
} 

或者,如果你不希望有安裝一個新的模塊:

use Encode 'find_encoding'; 
my $utf8 = find_encoding('utf8'); 

my $csv = Text::CSV->new({ binary => 1, eol => "\015\012" }); 
open my $fh, '>:raw', 'Foo.csv'; 
my $sth = $dbh->prepare("SELECT * FROM Foo"); 
$sth->execute(); 
# I'm assuming your field names are ASCII: 
$csv->print($fh, $sth->{NAME_lc}); # or NAME or NAME_uc 

while (my $row = $sth->fetchrow_arrayref) { 
    $csv->print($fh, [ map { $utf8->encode($_) } @$row ]); 
}