in reply to Re^4: Help !!! Symbolic Math Factroize Subroutine is clobbering my hash
in thread Help !!! Symbolic Math Factroize Subroutine is clobbering my hash

The array needs to be reset.

If the array is going to be "populated with other items", then a new array needs to be created. The  foo() function above creates a single array  @this_array and then puts things into and takes things out of it, but the location (and thus the reference address) of the array never changes; in the end, you wind up with a bunch of references to the same empty array (because the last thing you did to it was empty it).

c:\@Work\Perl\monks>perl -wMstrict -MData::Dumper -le "sub foo { ;; my @this_array; my %this_hash; ;; foreach my $something (0 .. 4) { ;; push(@this_array, $something); ;; my $key = $something + 1000; $this_hash{$key} = \@this_array; ;; @this_array = (); ;; } ;; return(\%this_hash); } ;; my $hash_ref = foo(); print Dumper $hash_ref; " $VAR1 = { '1002' => [], '1001' => $VAR1->{'1002'}, '1004' => $VAR1->{'1002'}, '1000' => $VAR1->{'1002'}, '1003' => $VAR1->{'1002'} };
(The repeated appearance of the expression  $VAR1->{'1002'} just means that the values of those keys all use the value of the previous key; all hash values are references to the same empty array.)

If you want references to a bunch of different arrays (possibly containing different things), you must repeatedly create a new lexical array and reference it. Maybe something like

c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "sub foo { ;; my %this_hash; ;; foreach my $something (0 .. 4) { ;; my @this_array; push(@this_array, $something); ;; my $key = $something + 1000; $this_hash{$key} = \@this_array; ;; } ;; return(\%this_hash); } ;; my $hash_ref = foo(); dd $hash_ref; " { 1000 => [0], 1001 => [1], 1002 => [2], 1003 => [3], 1004 => [4] }
Note that because  @this_array is created anew each time through the loop, there is no need ever to empty it. Note also that there are neater and IMHO better ways to create references to anonymous arrays, but that's an implementation and style discussion.

Replies are listed 'Best First'.
Re^6: Help !!! Symbolic Math Factroize Subroutine is clobbering my hash
by ipreferperl (Novice) on Dec 26, 2014 at 03:57 UTC
    Oh.. I see the error in my ways...you suggestion worked wonderfully... I should not have made this_array static. Did this by declaring this in the subroutine variable declaration ... Many thanks and a Merry Christmas !!!