简体   繁体   中英

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

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM