我有一个csv,第一列是一个标签,后面跟着逗号分隔值:
LabelA,45,56,78,90
LabelB,56,65,43,32
LabelC,56,87,98,45我希望第一列(LabelA等)是散列中的键,其数值位于一个数组中。
我可以将文件读入数组或标量,但我不确定之后该做什么。建议??
编辑:好的,看起来像是将值赋给了一个键..but我的例子中逗号分隔的数字呢?他们要去哪里?它们是否在%hash中?如果是这样的话,你可以进一步简化你的解释吗?谢谢。
发布于 2009-06-18 21:07:07
好吧,让我们假设没有特殊的字符等等。
首先打开文件:
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;发布于 2009-06-18 21:13:56
就我个人而言,我喜欢Text::CSV_XS和IO::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;
}发布于 2009-06-18 20:57:13
参见perlfunc split和perldsc。
创建一个hash of array references
您的数据结构应该如下所示:
my %foo = (
LabelA => [ 2, 3, 56, 78, 90 ],
LabelB => [ 65, 45, 23, 34, 87 ],
LabelC => [ 67, 34, 56, 67, 98 ],
);https://stackoverflow.com/questions/1015061
复制相似问题