zz0896
zz0896

Reputation: 11

Cannot locate error causing Perl warning: Use of unitialized value in concatenation (.) or string

I'm trying to program a File I/O for the first time and I don't understand why I'm getting this error in my for loop (line 22 or line 3 in sub routine printBestData). An extra pair of eyes would be greatly appreciated! Here's my code:

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";
    }
}

Upvotes: 1

Views: 48

Answers (1)

Gyrocode.com
Gyrocode.com

Reputation: 58880

There could be a few reasons:

  • ApgarMedicalBest.txt contains empty fields, for example 1,2,,4
  • ApgarMedicalBest.txt contains lines with less than 4 fields (defined in COLUMNS), for example 1,2,4

You could modify readBestData as follows to alleviate both problems:

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

Upvotes: 1

Related Questions