Perl中的动态哈希数组
我有一个如下的CSV文件:Perl中的动态哈希数组,perl,perl-module,Perl,Perl Module,我有一个如下的CSV文件: name,email,salary a,b@b.com,1000 d,e@e.com,2000 现在,我需要将其转换为Perl中的哈希映射数组,因此当我执行以下操作时: table[1]{"email"} 它回来了e@e.com. 我写的代码是: open(DATA, "<$file") or die "Cannot open the file\n"; my @table; #fetch header line $line = &l
name,email,salary
a,b@b.com,1000
d,e@e.com,2000
现在,我需要将其转换为Perl中的哈希映射数组,因此当我执行以下操作时:
table[1]{"email"}
它回来了e@e.com.
我写的代码是:
open(DATA, "<$file") or die "Cannot open the file\n";
my @table;
#fetch header line
$line = <DATA>;
my @header = split(',',$line);
#fetch data tuples
while($line = <DATA>)
{
my %map;
my @row = split(',',$line);
for($index = 0; $index <= $#header; $index++)
{
$map{"$header[$index]"} = $row[$index];
}
push(@table, %map);
}
close(DATA);
但是我没有得到想要的结果。。你能帮忙吗??提前感谢…这一行
push(@table, %map)
应该是
push(@table, \%map)
您希望表是散列引用的列表;您的代码将%map中的每个键和值作为一个单独的元素添加到列表中。这里不需要重新设计轮子。你可以用这个
也许是这样的:
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
my @table;
chomp(my $header = <DATA>);
my @cols = split /,/, $header; # Should really use a real CSV parser here
while (<DATA>) {
chomp;
my %rec;
@rec{@cols} = split /,/;
push @table, \%rec;
}
say $table[1]{email};
__END__
name,email,salary
a,b@b.com,1000
d,e@e.com,2000
使用Text::CSV解析CSV文件。引用,而不是地址。嗯,两者有什么不同?引用的值可能是地址,但不一定是地址;这只是一个实现细节。
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
my @table;
chomp(my $header = <DATA>);
my @cols = split /,/, $header; # Should really use a real CSV parser here
while (<DATA>) {
chomp;
my %rec;
@rec{@cols} = split /,/;
push @table, \%rec;
}
say $table[1]{email};
__END__
name,email,salary
a,b@b.com,1000
d,e@e.com,2000