【问题标题】:Using DBI::CSV module of Perl. Get undef for empty string while parsing the csv使用 Perl 的 DBI::CSV 模块。解析csv时获取空字符串的undef
【发布时间】:2014-02-09 16:33:32
【问题描述】:

我在 Perl 中使用 DBI::CSV 模块来解析我的 csv 并对数据运行查询。

我的数据是这样的

1001|23|1|loading  
1012|25||loading  

我希望第二行中的第三个字段是 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。
我将不胜感激这里的任何帮助。谢谢

【问题讨论】:

    标签: perl csv perl-module dbi


    【解决方案1】:

    您将@cols 声明为一个数组,然后为它分配一个数组引用,即您只初始化它的第一个元素。不要对数组使用方括号,仅用于数组引用:

    my @cols = ( "col1", "col2", "col3", "col4" );
    

    【讨论】:

      【解决方案2】:

      替换:

      $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'
                          }
              };
      

      【讨论】:

      • 我已经添加了您的建议,但我仍然得到与空字符串相同的结果。
      • 我运行了你的代码和你的示例,得到了你想要的输出,所以我不知道你的代码有什么问题,你上面的代码和你的完全一样吗正在运行吗?
      • 是的,完全一样。
      • 你看到我的$result 转储了吗?它正在使用您的代码和我的小修复
      • 是的,但不知道为什么我没有得到预期的结果
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-14
      • 1970-01-01
      • 1970-01-01
      • 2019-10-19
      • 2017-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多