2012-10-22 21 views
0

我正在使用DBD::CSV來顯示csv數據。有時文件不包含列名,所以我們必須手動定義它。但是在我遵循這些文檔之後,我陷入瞭如何使skip_first_row屬性工作的問題。我的代碼是:如何使用DBD :: CSV手動指定列名稱?

#! perl 
use strict; 
use warnings; 
use DBI; 

my $dbh = DBI->connect("dbi:CSV:", undef, undef, { 
    f_dir   => ".", 
    f_ext   => ".txt/r", 
    f_lock   => 2, 
    csv_eol   => "\n", 
    csv_sep_char  => "|", 
    csv_quote_char => '"', 
    csv_escape_char => '"', 
    csv_class  => "Text::CSV_XS", 
    csv_null   => 1, 
    csv_tables  => { 
     info => { 
      file => "countries.txt" 
     } 
    }, 
    FetchHashKeyName => "NAME_lc", 
}) or die $DBI::errstr; 

$dbh->{csv_tables}->{countries} = { 
    skip_first_row => 0, 
    col_names => ["a","b","c","d"], 
}; 

my $sth = $dbh->prepare ("select * from countries limit 1"); 
$sth->execute; 
while (my @row = $sth->fetchrow_array) { 
    print join " ", @row; 
    print "\n" 
} 
print join " ", @{$sth->{NAME}}; 

的countries.txt文件是這樣的:

AF|Afghanistan|A|Asia 
AX|"Aland Islands"|E|Europe 
AL|Albania|E|Europe 

但是,當我跑這個腳本,它返回

AX Aland Islands E Europe 
AF AFGHANISTAN A ASIA 

我希望它要麼退貨:

AF AFGHANISTAN A ASIA 
a b c d 

a b c d 
a b c d 

有沒有人知道這裏發生了什麼?

+0

感謝您指出我糾正了問題。 –

+0

讓我進一步細化我的問題,說清楚。 –

+0

我更新了問題。 –

回答

0

由於某些原因,與文檔相反,除非將它們傳遞給connect,否則不會看到每個表格設置。

my $dbh = DBI->connect("dbi:CSV:", undef, undef, { 
    f_dir   => ".", 
    f_ext   => ".txt/r", 
    f_lock   => 2, 
    csv_eol   => "\n", 
    csv_sep_char  => "|", 
    csv_quote_char => '"', 
    csv_escape_char => '"', 
    csv_class  => "Text::CSV_XS", 
    csv_null   => 1, 
    csv_tables  => { 
     countries => { 
      col_names => [qw(a b c d)], 
     } 
    }, 
    FetchHashKeyName => "NAME_lc", 
}) or die $DBI::errstr; 

然後正常工作:

my $sth = $dbh->prepare ("select * from countries limit 1"); 
$sth->execute; 

print "@{ $sth->{NAME} }\n";  # a b c d 

while (my $row = $sth->fetch) { 
    print "@$row\n";    # AF Afghanistan A Asia 
} 
+0

我更新了我的答案以匹配更新後的問題。 (我只使用'fetch'而不是'fetchrow_arrayref',僅用於視覺原因。) – ikegami

+0

'skip_first_row => 0'在使用'col_names'時是多餘的,所以我沒有使用它。 – ikegami