No that didn't work
I know the problem is when I pass the hash into the array it is always the same memory reference. Therefore when I access the array every hash reference will be the same and print out the same value. | [reply] |
...the problem is when I pass the hash into the array it is always the same memory reference. Therefore when I access the array every hash reference will be the same and print out the same value.
It's not clear to me exactly what you're doing (because, of course, you don't supply a Short, Self Contained, Correct (Compilable), Example), but my guess is that it's somthing like this:
c:\@Work\Perl\monks>perl -wMstrict -le
"my @docArray;
my %termsFreq;
;;
for my $x (0, 4, 8) {
%termsFreq = ($x .. $x+3);
push @docArray, \%termsFreq;
}
;;
for my $hashref (@docArray) {
for my $k (sort { $a <=> $b } keys %$hashref) {
printf qq{$k => $hashref->{$k} };
}
print '';
}
"
8 => 9 10 => 11
8 => 9 10 => 11
8 => 9 10 => 11
In this example, the content of the %termsFreq hash is repeatedly changed, but it's always the same hash, i.e., always the same location in memory. The final content of that location is the last set of data you put into it. Note that the %termsFreq hash is defined outside the loop.
In contrast, consider:
c:\@Work\Perl\monks>perl -wMstrict -le
"my @docArray;
;;
for my $x (0, 4, 8) {
my %termsFreq = ($x .. $x+3);
push @docArray, \%termsFreq;
}
;;
for my $hashref (@docArray) {
for my $k (sort { $a <=> $b } keys %$hashref) {
printf qq{$k => $hashref->{$k} };
}
print '';
}
"
0 => 1 2 => 3
4 => 5 6 => 7
8 => 9 10 => 11
In this example, a new hash is created within the loop and initialized on each pass through the loop, and its reference is taken and push-ed to the array. All of these newly-created hashes (and their contents and addresses) are and remain unique.
Give a man a fish: <%-{-{-{-<
| [reply] [d/l] [select] |