No such thing as a small change | |
PerlMonks |
Re: Push array to hashby haukex (Archbishop) |
on Jun 25, 2020 at 07:03 UTC ( [id://11118491]=note: print w/replies, xml ) | Need Help?? |
The first structure appears just fine, but subsequent pushes only show as "${$VAR1}->[0]" - not sure why? As BillKSmith mentioned, what's going on here is that you have one hash %lag_detail, and every time you push a reference to that hash onto the array, you're pushing a reference to the same one hash. This also means that when you write %lag_detail = ( ... );, you're resetting that one hash, and therefore every reference to the hash will reflect that change, which is unlikely to be what you want. That's what ${$VAR1}->[0] means: Data::Dumper is trying to tell you that the other elements of the array refer to the exact same data structure. In essence, this is what's going on - note how both times, a reference to the same hash is pushed onto the array:
There are a couple of ways to fix this. The one that I think is probably most applicable in this case is to change from using a hash %lag_detail to a reference to an anonymous hash (hashref), as in:
The reason this works is that with $lag_detail = { ... }, you're actually allocating a new anonymous hash every time and getting a reference to it. See perlreftut and perlref if you're unsure about some of the details of references. Just for completeness, in addition to the (shallow) copying of the hash that BillKSmith suggested, a very common solution to this problem is to define the hash inside the loop, which also gets you a new hash on every iteration of the loop:
However, since it looks to me like you're probably parsing a multiline data strucutre and don't want to push a record onto the array until it is complete, I think this is unlikely to be the correct fix in your case.
In Section
Seekers of Perl Wisdom
|
|