簡體   English   中英

如何使用DBD :: CSV手動指定列名?

[英]How to manually specify the column names using DBD::CSV?

我正在使用DBD :: CSV顯示CSV數據。 有時文件不包含列名,因此我們必須手動定義它。 但是,在遵循了文檔之后,我陷入了如何使屬性skip_first_row工作的困擾。 我的代碼是:

#! 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}};

country.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

有誰知道這是怎么回事嗎?

由於某種原因,與文檔相反,除非將它們傳遞給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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM