I wrote the following Perl function
sub Outputing
{
my $featureMatrix = shift;
my $indexRow = shift;
my $fileName = "/projectworkspace/input.dat";
open(DATA, "> $fileName");
printf DATA "%d", $#$indexRow;
print DATA "\n";
my $numDataPoints = $#{$featureMatrix{$indexRow->[1]}};
printf DATA "%d", $numDataPoints;
print DATA "\n";
close DATA;
}
I calling Outputing as follows:
Outputing($matrix, $Rows);e
$matrix is a hash of array, whose structure is like this
my $matrix
= { 200 => [ 0.023, 0.035, 0.026 ],
110 => [ 0.012, 0.020, 0,033],
};
Rows is an array storing the sorted key of matrix, it is obtained as follows
my @Rows = sort keys %matrix;
both matrix and Rows are used as parameters passed to Outputing.
The printed out $numDataPoints is -1, which is not correct? I do not know which might be the reason that causes this problem? If we use the above example, and assume $indexRow->[1]=110, then $numDataPoints should be 2. I am not sure whether the $#{$featureMatrix{$indexRow->[1]}}; is the correct way to get the size of this array.
Assuming that you’ve included all the relevant code, this:
should be this:
and this:
should be this:
That is, the problem is that in some places, you’re using a hash named
%featureMatrix, and in others, you’re using a hashref named$featureMatrixthat refers to an anonymous hash.You should be using
use warningsanduse strictto prevent such mistakes: those would have prevented you from using%featureMatrixwhen you’ve only declared$featureMatrix. (Actually,use warningsmight not help in this case — it could detect if you used%featureMatrixexactly once, but in your case, you use it a few times — butuse strictwould almost certainly have helped.)