我在Perl中使用DBI :: CSV模块来解析我的csv并对数据运行查询。
我的数据是这样的
1001|23|1|loading
1012|25||loading
我希望第二行中的第3个字段是undef,这是我无法实现的。我将字段作为空字符串而不是undef,这是我试过的代码片段。
use strict;
use warnings "all";
use Text::CSV_XS;
use DBI;
my $dbh = DBI->connect( "dbi:CSV:", undef, undef, {
csv_sep_char => "|",
f_dir => ".",
csv_eol => "\n",
csv_empty_is_undef => 1,
csv_blank_is_undef => 1,
csv_quote_char => undef,
csv_escape_char => undef,
csv_always_quote => undef,
f_ext => ".csv",
f_enc => "utf-8",
csv_class => "Text::CSV_XS",
RaiseError => 1,
PrintError => 1
}
);
my @cols = ("col1", "col2", "col3", "col4");
$dbh->{'csv_tables'}{'info'} = { 'file' => "file.csv", col_names => \@cols };
my $result =$dbh->selectall_hashref( "select col1,col2,col3,col4 from info where col1 = 1012", "col1")
#gives the following result
0 HASH(0x992573c)
1012 => HASH(0x9900e90)
'col1' => 1012
'col2' => '25'
'col3' => ''
'col4' => 'loading'
我期待col3的值为undef here 这里的任何帮助我都会感激。感谢
答案 0 :(得分:1)
您将@cols声明为数组,但随后为其分配数组引用,即您只初始化其第一个元素。不要对数组使用方括号,仅用于数组引用:
my @cols = ( "col1", "col2", "col3", "col4" );
答案 1 :(得分:0)
替换:
$dbh->{'csv_tables'}{'info'} = { 'file' => "file.csv", col_names => \@cols };
使用:
$dbh->{'csv_tables'}{'info'} = { 'file' => "file.csv", col_names => @cols };
结果:
$VAR1 = {
'1012' => {
'col3' => undef,
'col1' => '1012',
'col2' => '25',
'col4' => 'loading'
}
};