【发布时间】:2016-04-20 22:25:49
【问题描述】:
我有这种形式的 CSV 数据:
Sl.No, Label, Type1, Type2...
1, "label1", Y, N, N...
2, "label2", N, Y, Y...
...
其中“Y”和“N”表示是否将相应的标签打印到文件中。
while ( <$fh> ) { #Reading the CSV file
$filter = $_;
chomp $filter;
$filter =~ tr/\r//d;
if ( $. == 1 ) {
@fieldNames = split ",", $filter;
}
else {
@fields = split ",", $filter;
$numCustomers = scalar(@fields) - 2;
push @labels, $fields[2];
for ( $i = 0; $i < $numCustomers; $i++ ) {
for ( $j = 0; $j < scalar(@labels); $j++ ) {
$customer[$i][$j] = $fields[ 2 + $i ];
}
$custFile = "customer" . $i . "_external.h";
open( $fh1, ">", $custFile ) or die "Unable to create external header file for customer $i";
}
}
}
for ( $i = 0; $i < scalar(@labels); $i++ ) {
for ( $j = 0; $j < $numCustomers; $j++ ) {
$Hash{ $fieldNames[ 2 + $i ] }->{ $labels[$i] } = $customer[$j][$i];
push @aoh, %Hash; #Array of hashes
}
}
my @headerLines = read_file($intFile); # read the internal file, and copy only
# those lines that are not marked with
# "N" in the CSV file to the external file.
# iterate over elements of each hash and print the labels only if value is 'Y'
foreach my $headerLine (@headerLines) {
chomp $headerLine;
for $i ( 0 .. $#aoh ) {
for my $cust1 ( sort keys %{ $aoh[$i] } ) { #HERE
for my $reqLabel1 ( keys %{ $aoh[$i]{$cust1} } ) {
print "$cust1, $reqLabel1 : $aoh[$i]{$cust1}{$reqLabel1}\n";
if ( $aoh[$i]{$cust1}{$reqLabel1} eq "Y" ) {
for ( $j = 0; $j < $numCustomers; $j++ ) {
$req[$j][$i] = $reqLabel1;
}
}
else {
for ( $j = 0; $j < $numCustomers; $j++ ) {
$nreq[$j][$i] = $reqLabel1;
}
}
}
}
if ( grep { $headerLine =~ /$_/ } @nreq ) {
next; #Don't print this line in the external file
}
else {
print $fh1 $headerLine . "\n"; #print this line in the external file
}
}
}
这抱怨“不能使用字符串 Type1 作为哈希 REF”,指的是标记为 #HERE 的行。
我尝试过到处转储数据结构,但我不确定这是从哪里出现的。
任何见解将不胜感激。
我收到反馈说使用Text::CSV 会是更好的解决方案。它将如何减少使用嵌套数据结构的需要?
【问题讨论】:
-
给定样本输入的预期输出是什么?
-
$intFile中的行被写入外部文件(print $fh1 $headerLine."\n";);除非该行在 CSV 中标记为“N”。 -
CSV 中的每个“类型”都有一个单独的外部文件。
-
你到底想在这里完成什么?因为我会指出 -
Text::CSV支持命名列,所以你实际上不必为哈希和切片而烦恼。 -
总是
use strict; use warnings;