在perl中使用TEXT :: CSV_XS模块将CSV文件转换为哈希结构 [英] To Convert CSV File to Hash Structure using TEXT::CSV_XS Module in perl
问题描述
下面是用于读取csv文件并将其转换为哈希的代码.密钥取决于用户所需的密钥列数.
I've below code which is used to read a csv file and convert to hash. The Keys are dependent on the number of key columns that user need.
use warnings;
use strict;
my %hash;
my $KeyCols = 2;
while (<DATA>) {
chomp;
my @cols = split /,/, $_, $KeyCols+1;
next unless @cols > $KeyCols;
my $v = pop @cols;
my $k = join '', @cols;
$hash{$k} = $v;
}
我需要帮助来使用TEXT :: CSV_XS包实现相同的逻辑,以提高效率.请帮忙.
I need help in achieving the same logic using TEXT::CSV_XS package for efficiency. Please help.
推荐答案
使用Text :: CSV_XS的真正原因是为了确保正确性.它不会比您拥有的要快,但是它将在您失败的地方起作用.
The real reason for using Text::CSV_XS is for correctness. It's not going to be faster than what you have, but it will work where yours will fail.
use Text::CSV_XS qw( );
my $csv = Text::CSV_XS->new({
auto_diag => 2,
binary => 1,
});
my %hash;
while ( my $row = $csv->getline(\*DATA) ) {
$hash{ $row->[0] . $row->[1] } = $row;
}
直接将字段串联在一起(不带分隔符)似乎很奇怪.
Concatenating the fields together directly (without a separator) seems really odd.
上面的方法使该值成为一个字段数组,而不是CSV.如果您想要CSV原始格式的CSV,则需要将它们重新编码为CSV.
The above makes the value an array of fields rather than CSV. If you want CSV as in the original, you will need to re-encode them into CSV.
my %hash;
while ( my $row = $csv->getline(\*DATA) ) {
my ($k1, $k2) = splice(@$row, 0, 2);
$csv->combine(@$row);
$hash{ $k1 . $k2 } = $csv->string();
}
这篇关于在perl中使用TEXT :: CSV_XS模块将CSV文件转换为哈希结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!