CSV转化为哈希 [英] CSV into hash

查看:121
本文介绍了CSV转化为哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我希望第一列(LabelA等)成为数组中的数字值的哈希键。



我可以将文件读入数组或标量,但我不知道在那之后要做什么。建议?

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

解决方案

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



首先打开文件:

 打开我的$ fh,'<','some.file .csv'或死无法打开:$!; 

然后你从循环中读取它:

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

之后,您将删除尾随的白色字符(\\\
和其他字符):

  $ line =〜s / \ S * \z //; 

然后将它分成数组:

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

当它在数组中时,您将获得数组中的第一个元素:

  my $ key = shift @array; 

并将其存储在哈希中:

  $ hash {$ key} = \ @ array; 

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

全码:

  my%hash; 
打开我的$ fh,'<','some.file.csv'或死无法打开:$!;
while(my $ line =< $ fh>){
$ line =〜s / \ s * \ z //;
my @array = split /,/,$ line;
my $ key = shift @array;
$ hash {$ key} = \ @ array;
}
close $ fh;


I have a csv with the first column a label followed by comma separated values:

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

I'd like the first column (LabelA etc) to be the Key in a hash with the numeric values in an array.

I can read the file into an array or scalar but I'm not sure what to do after that. Suggestions??

Edit: Ok, so it looks like this assigns the value to a key ..but what about the comma delimited numbers in my example? Where are they going? Are they in %hash ? If so could you maybe dumb down your explanation even further? Thanks.

解决方案

Well, let's assume that there are no special characters and so on.

First you open the file:

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

Then you read from it in loop:

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

Afterwards, you remove trailing white characters (\n and others):

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

And split it into array:

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

When it's in array, you get first element off the array:

my $key = shift @array;

And store it in hash:

$hash{$key} = \@array;

(\@array means reference to array).

Whole code:

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;

这篇关于CSV转化为哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆