我正在使用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"
}
countries.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
答案 0 :(得分:2)
$sth->{NAME}
,$sth->{NAME_lc}
和$sth->{NAME_uc}
返回对包含名称的数组的引用。
my $sth = $dbh->prepare("select * from countries limit 1");
$sth->execute;
print "$_\n" for @{ $sth->{NAME} };