open TMP, "datafile.txt" || die ("Could not open data file\n") ; my @input_data = ; close TMP; my $record_count = 0; # Loop through the array for my $element (@input_data) { chomp; @first = split(",", $element ) ; my $jcount = 0; my @result; # Loop through the array again for my $inside_elem (@input_data) { chomp; @second = split(",", $inside_elem) ; # Build only elements below the diagonal last if ( $jcount++ > $record_count ) ; # Covariance logic # No issues with the logic # sum of products of corresponding elements in the arrays $sum = 0; $count = 0; for (@first) { $sum += $_ * $second[$count++] ; } $sum /= scalar(@first) ; push @result, $sum ; } my $str_to_write = join(", ", @result)."\n" ; undef @result ; # Open the output file handler in append mode. open TMP, ">>Outfile.txt" || die ("Could not open output file "); print TMP $str_to_write; close TMP ; }