Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re^5: Creating CSV term document matrix from a hash stored in multideminsional array

by AnomalousMonk (Archbishop)
on Mar 04, 2017 at 03:03 UTC ( [id://1183621] : note . print w/replies, xml ) Need Help??


in reply to Re^4: Creating CSV term document matrix from a hash stored in multideminsional array
in thread Creating CSV term document matrix from a hash stored in multideminsional array

...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:  <%-{-{-{-<