如何在perl中创建数组的动态哈希?

时间:2014-03-10 11:34:49

标签: arrays perl csv hash

我有两个用于映射的文件。一个是CSV,另一个是config(INI)文件。

[config.ini]
char=1 
int=3
float=4
double=8

[myfile.csv]
char,int,long int,float,double,long double
gender,id,salary,salary,bonus,LTA
name,pan,account,tips,interest,lotery

现在我想创建一个数组哈希来存储它们,结构应如下所示:

my %mappings = (
ATTRIB => {
'char' => [ qw ( gender name ) ],
'id' => [ qw ( id pan)],
'long int' =>[qw (  salary account ) ],
'float' => [ qw (salary tips) ],
'double' => [ qw ( bbonus interest) ],
'long double' = >[( LTA lotery)],
},
);

while (<INI>) {
chomp;
split(/\=/); ## Collect the elements of this line
$headers[$1]=[$2];          
}
close INI;

while (CSV)
{
@array = split(/,/, $_);
}
close CSV;

现在我想尝试做

@{$data_out{$val}}= @{$csv_data{$val}};

但它不起作用。还有一件事,我如何访问第一批数据?     例如: - 性别,身份,工资,工资,奖金,利息

1 个答案:

答案 0 :(得分:0)

use strict;
use warnings;

my @columns;
while (<DATA>) {
    chomp;
    my @data = split ',';

    for my $i (0..$#data) {
        push @{$columns[$i]}, $data[$i];
    }
}

my %attrib = map {shift @$_ => $_} @columns;

my %mapping = (ATTRIB => \%attrib);

use Data::Dump;
dd \%mapping;


__DATA__
char,int,long int,float,double,long double
gender,id,salary,salary,bonus,LTA
name,pan,account,tips,interest,lotery

输出

{
  ATTRIB => {
    "char"        => ["gender", "name"],
    "double"      => ["bonus", "interest"],
    "float"       => ["salary", "tips"],
    "int"         => ["id", "pan"],
    "long double" => ["LTA", "lotery"],
    "long int"    => ["salary", "account"],
  },
}