Satya's blog - Array refs in perl
Using HTML::Template,
I was trying to put an array
inside a loop onto another array...
nothing like code snippets:
while(stuff) { # more stuff push @arr2, {K1 => \@arr1, K2 => $otherstuff}; }People will recognize that an anonymous hash with keys K1 and K2 is being pushed onto arr2. At a certain point in the loop, given certain conditions, @arr1 needs to be blanked and emptied. But I wans't getting the right results. Data::Dumper showed that the next iteration pointed back at the first instance of arr1. No, "instance" is the wrong word. The array pointer was still the same, so by assigning the pointer (a.k.a. reference) to K1 I was clobbering whatever happened to be in @arr1 before I blanked it, in the next iteration after blanking. So here's the fix: while(stuff) { # more stuff push @arr2, {K1 => [ @arr1] , K2 => $otherstuff}; }That creates an anonymous array which is assigned as the value for K1, and that anon array's contents come from @arr1. Problem solved. |
|