CSV变为哈希

时间:2009-06-18 20:37:25

标签: perl hash

我有一个csv,第一列是标签,后跟逗号分隔值:

LabelA,45,56,78,90
LabelB,56,65,43,32
LabelC,56,87,98,45

我希望第一列(LabelA等)成为数组中数值的散列中的Key。

我可以将文件读入数组或标量但我不确定在那之后该怎么做。建议?

编辑: 好的,所以它看起来像是将值赋给一个键..但是我的例子中逗号分隔的数字怎么样?他们要去哪?他们是%哈希?如果是这样,你可能会进一步愚弄你的解释?感谢。

5 个答案:

答案 0 :(得分:10)

就个人而言,我喜欢Text::CSV_XSIO::File模块:

use Text::CSV_XS;
use IO::File;

# Usage example:
my $hash_ref = csv_file_hashref('some_file.csv');

foreach my $key (sort keys %{$hash_ref}){
   print qq{$key: };
   print join q{,}, @{$hash_ref->{$key}};
   print qq{\n};
}

# Implementation:
sub csv_file_hashref {
   my ($filename) = @_;

   my $csv_fh = IO::File->new($filename, 'r');
   my $csv = Text::CSV_XS->new ();

   my %output_hash;

   while(my $colref = $csv->getline ($csv_fh))
   {
      $output_hash{shift @{$colref}} = $colref;
   }

   return \%output_hash;
}

答案 1 :(得分:7)

好吧,我们假设没有特殊字符等等。

首先打开文件:

open my $fh, '<', 'some.file.csv' or die "Cannot open: $!";

然后你在循环中读取它:

while (my $line = <$fh>) {

然后,删除尾随白色字符(\ n和其他):

$line =~ s/\s*\z//;

将其拆分为数组:

my @array = split /,/, $line;

当它在数组中时,你从数组中得到第一个元素:

my $key = shift @array;

并将其存储在哈希:

$hash{$key} = \@array;

(\ @ array表示对数组的引用)。

整个代码:

my %hash;
open my $fh, '<', 'some.file.csv' or die "Cannot open: $!";
while (my $line = <$fh>) {
  $line =~ s/\s*\z//;
  my @array = split /,/, $line;
  my $key = shift @array;
  $hash{$key} = \@array;
}
close $fh;

答案 2 :(得分:1)

请参阅perlfunc splitperldsc

  1. 阅读每一行。
  2. Chomp it。
  3. 将其拆分为逗号。
  4. 使用结果中的第一个值作为HoA的密钥。
  5. 其他值成为数组。
  6. 将数组存储在密钥下的哈希中。
  7. ...
  8. 利润!!!
  9. 制作hash of array references

    您的数据结构应如下所示:

    my %foo = (
        LabelA => [  2, 3,  56, 78, 90 ],
        LabelB => [ 65, 45, 23, 34, 87 ],
        LabelC => [ 67, 34, 56, 67, 98 ],
    );
    

答案 3 :(得分:0)

Text::CSV::Hashify

将CSV文件转换为Perl哈希:

{{1}}

答案 4 :(得分:0)

我认为这样做也更容易。

$ refhashvariable将是对哈希数组的引用。

每个哈希包含标题(作为哈希键)和一个CSV行的值。 该数组包含CSV中所有行的哈希。

use Text::CSV_XS qw( csv );
$refhashvariable = csv(
    in      => "$input_csv_filename",
    sep     => ';',
    headers => "auto"
);    # as array of hash

这对我有用。我没有尝试过CSV没有标题的情况。

相关问题