hsfrey has asked for the wisdom of the Perl Monks concerning the following question:

I'm running ActivePerl 1003 on Windows. If I write: %newhash={}; I find that the hash has one entry, with key being HASH(address) and value=null. That entry remains as I add others, and is included whenever I traverse the hash. In order to get a clean hash, I have to write: undef %newhash; If this is a general problem, why haven't I seen it mentioned anywhere? If it's not a general problem, is it peculiar to ActivePerl 1003? Or is it just me? ;-)

Replies are listed 'Best First'.
Re: initializing a hash leaves garbage
by FunkyMonk (Bishop) on Jul 19, 2008 at 06:43 UTC
    {} creates an empty reference to an anonymous hash. To initialiase a hash (not that it's needed), use (). Better still, use strictures (use strict; use warnings;) at the start of all your programs and declare all your variables before use with my %hash; etc.

    You'll probably find the Perl data structures cookbook is worth reading


    Unless I state otherwise, all my code runs with strict and warnings
Re: initializing a hash leaves garbage
by Fletch (Bishop) on Jul 19, 2008 at 15:45 UTC

    Had you been using warnings you would have gotten griped at.

    $ perl -Mwarnings -le 'my %hash = {};' Reference found where even-sized list expected at -e line 1.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: initializing a hash leaves garbage
by Anonymous Monk on Jul 19, 2008 at 08:11 UTC
    undef %foo; seems perfectly sensible

      But it's totally unnecessary. my %hash;, which you need to do anyway, creates and empty hash.