2013-03-25 34 views
0

哈希值的動態數組我有一個CSV文件中像這樣:在Perl

name,email,salary 
a,[email protected],1000 
d,[email protected],2000 

現在,我需要這種轉換在Perl哈希映射的陣列,所以當我做這樣的事情:

table[1]{"email"} 

它返回[email protected]

我寫的代碼是:

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); 

但我沒有得到期望的結果.. u能幫助?在此先感謝...

+1

使用'文字:: CSV'解析一個CSV文件。 – chepner 2013-03-25 13:47:47

回答

5

此行

push(@table, %map) 

應該

push(@table, \%map) 

你想table成爲哈希引用列表;您的代碼將%map中的每個鍵和值作爲單獨的元素添加到列表中。

+0

非常感謝! :)錯過了這一點..地址:) – Srikrishnan 2013-03-25 14:03:00

+1

「參考」,而不是「地址」。 – 2013-03-25 15:29:26

+0

嗯,這兩個不同? – Srikrishnan 2013-03-27 10:28:41

4

這裏沒有必要重新發明輪子。你可以用Text::CSV module來做到這一點。

#!/usr/bin/perl 

use strict; 
use warnings; 
use v5.16; 
use Text::CSV; 

my $csv = Text::CSV->new; 
open my $fh, "<:encoding(utf8)", "data.csv" or die "data.csv: $!"; 
$csv->column_names($csv->getline ($fh) ); 
while (my $row = $csv->getline_hr ($fh)) { 
    say $row->{email}; 
} 
2

像這樣的東西可能:

#!/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,[email protected],1000 
d,[email protected],2000