Today I spent a few hours on a nasty perl coding error. Without going into too much detail, by using that piece of code in some loop processing some data …
1: ...
2: $entry_data->{"content"} = $content;
3: $entry_data->{"year"} = $current_year;
4: push(@entries,$entry_data);
5: .…
.. I ended up having always elements with the same content in my array “@entries” ( and it took me a while to figure that out as a root cause for my programs strange behavior ). Simply because I am storing a hash reference in that array, which is always the reference to the same hash if not modifying the code as follows:
1: ...
2: $entry_data->{"content"} = $content;
3: $entry_data->{"year"} = $current_year;
4: push(@entries,$entry_data);
5: $entry_data = {};
6: ...
This tiny little extra line “$entry_data = {}” ensures that perl creates a new hash and I add new hashes to my array instead of always overwriting the same hash.
Grrrr, my stupidity
.






June 23, 2009 at 8:00 pm
You’re probably not using the strict pragma. If you declare %entry_data with my (as strict recommends) in the smallest scope possible, you’ll avoid this problem.
June 24, 2009 at 7:55 am
Ah, good hint, thanks chromatic !
June 24, 2009 at 10:31 am
OK, chromatic, thought about this a bit further. The strict pragma would not have helped since I declared $entry_data globally and it has been a hash reference, not a hash.
Nevertheless, declaring that variable within the loop of course solves the issue and is kind of similar to the “fix” I described.
Of course I am to blame for using something like a global variable; no good practice and this is a nice example about a possible trap when doing this.