我正在尝试第一次编写文件I / O,我不明白为什么我在for循环中遇到此错误(子例程printBestData中的第22行或第3行)。额外的一双眼睛将非常感激!这是我的代码:
my (@bestData, @cushingData, @combinedData);
use constant BESTDATAFILEIN => "./ApgarMedicalBest.txt";
use constant CUSHINGDATAFILEIN => "./ApgarMedicalCushing.txt";
use constant DATAFILEOUT => "./MergedApgarMedical.csv";
use constant COLUMNS => 4;
sub readBestData {
my $IN;
my $counter = 0;
my @tempData = ();
@bestData = ();
open ($IN, '<', BESTDATAFILEIN);
while (<$IN>) {
@tempData = split(/,/);
for (my $i = 0; $i < COLUMNS; $i++) {
($bestData[$counter][$i] = $tempData[$i]);
}
$counter++;
}
close $IN;
}
sub printBestData {
my $size = @bestData;
for (my $i = 0; $i < $size; $i++) {
for (my $j = 0; $j < COLUMNS; $j++) {
#Error occurs in this line
print "$bestData[$i][$j] ";
}
print "\n";
}
}
答案 0 :(得分:1)
可能有几个原因:
ApgarMedicalBest.txt
包含空字段,例如1,2,,4
ApgarMedicalBest.txt
包含少于4
个字段的行(在COLUMNS
中定义),例如1,2,4
您可以按如下方式修改readBestData
以缓解这两个问题:
sub readBestData {
my $IN;
my $counter = 0;
my @tempData = ();
@bestData = ();
open ($IN, '<', BESTDATAFILEIN);
while (<$IN>) {
# Split string and avoid skipping empty fields
@tempData = split(/,/, $_, -1);
# If data contains required number of columns
if(scalar(@tempData) == COLUMNS){
for (my $i = 0; $i < COLUMNS; $i++) {
($bestData[$counter][$i] = $tempData[$i]);
}
}
$counter++;
}
close $IN;
}