Perl Coding Error: do not overwrite your hash !

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 smile_baringteeth.

Advertisements

3 Responses to “Perl Coding Error: do not overwrite your hash !”

  1. chromatic Says:

    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.

  2. amagard Says:

    Ah, good hint, thanks chromatic !

  3. Axel Magard Says:

    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.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: