找不到导致Perl警告的错误:在串联(。)或字符串中使用单位化值

时间:2015-05-02 19:34:29

标签: perl file concatenation string-concatenation

我正在尝试第一次编写文件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";
    }
}

1 个答案:

答案 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; 
}