加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

用于哈希的Perl CSV

发布时间:2020-12-15 23:34:41 所属栏目:大数据 来源:网络整理
导读:我有一个CSV文件,其中包含标题行和数据之前的注释文本,我想将其作为哈希进行进一步操作.主键具有散列将是两个数据值的组合.我如何能? 使用模式’index’搜索标题行 使用标题键 阅读其余文件. 示例CSV ####Description information of source of file.index,
我有一个CSV文件,其中包含标题行和数据之前的注释文本,我想将其作为哈希进行进一步操作.主键具有散列将是两个数据值的组合.我如何能?

>使用模式’index’搜索标题行
>使用标题键
>阅读其余文件.

示例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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读