2

我正在使用DBD::CSV来显示 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"],
  raw_header => 1,
};

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

country.txt 文件是这样的:

ISO_COUNTRY|COUNTRY_NAME|REGION_CODE|REGION_NAME
AF|Afghanistan|A|Asia
AX|"Aland Islands"|E|Europe
AL|Albania|E|Europe

但是当我运行这个脚本时,它返回

AF Afghanistan A Asia

我希望它返回:

ISO_COUNTRY COUNTRY_NAME REGION_CODE REGION_NAME

有谁知道如何使用 DBD::CSV 模块来实现这一点?

还有一个问题是col_names属性设置为什么没有生效?如何使其返回以下内容?

 a b c d
4

1 回答 1

2

$sth->{NAME}, $sth->{NAME_lc} and $sth->{NAME_uc} return a reference to an array containing the names.

my $sth = $dbh->prepare("select * from countries limit 1");
$sth->execute;
print "$_\n" for @{ $sth->{NAME} };
于 2012-10-22T16:56:38.580 回答