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

两盒软妹~` 提交于 2019-12-11 14:07:34

问题


I am using DBD::CSV to show csv data. Sometimes the file doesn't contain column names, so we have to manually define it. But after I followed the documentation, I got stuck with how to make the attribute skip_first_row work. The code I have is:

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

The countries.txt file is like this:

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

But when I ran this script, it returns

AX Aland Islands E Europe
AF AFGHANISTAN A ASIA

I expected it to either return:

AF AFGHANISTAN A ASIA
a b c d

or

a b c d
a b c d

Does any know what's going on here?


回答1:


For some reason, contrary to the documentation, it doesn't see the per-table settings unless you pass them to 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;

Then it works fine:

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
}


来源:https://stackoverflow.com/questions/13016794/how-to-manually-specify-the-column-names-using-dbdcsv

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!