7

ヘッダー行とデータの前にコメント テキストを含む CSV ファイルがあり、さらに操作するためにハッシュとして読み込みたいと考えています。主キーのハッシュは、2 つのデータ値の組み合わせになります。どうすればいいですか?

  1. パターン「index」を使用してヘッダー行を検索します
  2. キーにヘッダーを使用する
  3. ファイルの残りを読み込みます。

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'} )   
4

4 に答える 4

12

そのためには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;
于 2013-03-08T14:05:02.063 に答える
3

あなたはいつでも次のようなことをすることができます:

#!/usr/bin/env perl

use strict;
use warnings;

my %hash;
while( <DATA> ){ last if /index/ } # Consume the header
my $labels = $_;  # Save the last line for hash keys
chop $labels;
while(<DATA>){
    chop;
    my @a = split ',';
    my $idx = 0;
    my %h = map { $_ => $a[$idx++]} split( ",", $labels );
    $hash{ $a[1] . $a[2] } = \%h;
}

while( my ( $K, $H ) = each %hash ){
    print "$K :: ";
    while( my( $k, $v ) = each( %$H ) ) {
        print $k . "=>" . $v . "  ";
    }
    print "\n";
}

__DATA__

#
#
#
#
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
于 2013-03-08T13:25:44.560 に答える