Perl CSV 散列

标签 perl csv hash

我有一个 CSV 文件,其中包含标题行和数据之前的注释文本,我想将其作为哈希读入以进行进一步操作。主键具有哈希值,将是两个数据值的组合。我如何?

  • 使用模式 'index'
  • 搜索标题行
  • 使用键 header
  • 读入文件的其余部分。

  • 示例 CSV
    #
    #
    #
    #
    Description information of source of file.
    
    index,label,bit,desc,mnemonic
    6,370,11,three,THRE
    9,240,23,four,FOR
    11,120,n/a,five,FIV
    

    示例所需的哈希
    ( '37011' => { 'index' => '6', 'label' => '370', 'bit' => '11', 'desc' => 'three', 'mnemonic' => 'THRE'}, '24023' => {'index' => '9', 'label'  => '240', 'bit' => '23', 'desc' => 'four', 'mnemonic' => 'FOR'}, '120n/a' => {'index' => '11', 'label'  => '120', 'bit' => 'n/a', 'desc' => 'five', 'mnemonic' => 'FIV'} )   
    

    最佳答案

    您需要 Text::CSV模块:

    #!/usr/bin/env perl
    use strict;
    use warnings;
    use Data::Dumper;
    use Text::CSV;
    
    my $filename = 'test.csv';
    
    # watch out the encoding!
    open(my $fh, '<:utf8', $filename)
        or die "Can't open $filename: $!";
    
    # skip to the header
    my $header = '';
    while (<$fh>) {
        if (/^index,/x) {
            $header = $_;
            last;
        }
    }
    
    my $csv = Text::CSV->new
        or die "Text::CSV error: " . Text::CSV->error_diag;
    
    # define column names    
    $csv->parse($header);
    $csv->column_names([$csv->fields]);
    
    # parse the rest
    while (my $row = $csv->getline_hr($fh)) {
        my $pkey = $row->{label} . $row->{bit};
        print Dumper { $pkey => $row };
    }
    
    $csv->eof or $csv->error_diag;
    close $fh;
    

    关于Perl CSV 散列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15294807/

    相关文章:

    mongodb - perl:无法连接到 mongodb 服务器

    python - 在 python 上找不到用于导入 csv 的文件。文件路径正确,一切都已安装

    c - 使用 scanf 将 csv 文件读入 C 中的结构

    javascript - JavaScript 中的通用 2D 哈希?

    ruby-on-rails - 哈希覆盖哈希

    python - Perl 到 Python 正则表达式需要帮助

    arrays - 我怎样才能从这个数组生成排列?

    PHP:在 SQL 中插入时将每个数据放入单引号 (' ' )

    ruby - 检查 ruby​​ 散列是否包含大于 x 的值

    perl - 我如何使用 Perl 的 Inline::C?