http://www.perlmonks.org?node_id=322442

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

Hello all,

There is probably no way to do this, but I'll throw this question out there anyway. Is there any way to initialize a hash table so every 'key' (single or multi) is set to 0 ?

Basically, I'm parsing a database and I'm building a hash table with items I find in the database. I do not know what keys may be in the database ahead of time. Everything is working fine, but when I print out the hash table, some values are blank because no values matched (it's a multi-key hash table).

I hope this is clear, if not I'll try to explain better. Again, I'm guessing this is not possible just because I don't know the values of the keys ahead of time.

As always, thank in advance.

Replies are listed 'Best First'.
Re: Initializing a hash table
by thelenm (Vicar) on Jan 19, 2004 at 21:53 UTC

    Could you post a snippet of code that shows what you're currently doing? I would think that at the time when you print out the results, you could just print "0" if you detect that no entries exist. Depending on how you're building the hash, "detecting no entries" could mean using exists, or defined, or scalar keys %{$hash{'key'}}, or something else.

    -- Mike

    --
    XML::Simpler does not require XML::Parser or a SAX parser. It does require File::Slurp.
    -- grantm, perldoc XML::Simpler

Re: Initializing a hash table
by pg (Canon) on Jan 19, 2004 at 22:08 UTC

    To use hash, there is absolutely no initialization is needed.

    Now if whatever you supposed to use as hash key is not unique in your database, you cannot use straight one level hash as your storage.

    Try HoA(oH):

    • The entire table is a hash;
    • Table rows with the same key go into the same array.
    • Columns for each row go into the third level.
Re: Initializing a hash table
by grinder (Bishop) on Jan 19, 2004 at 22:02 UTC

    If I understand you correctly, it's not so much that you want to know how to initialise the hash, but what to do when a key you look for isn't there. If that's the case, you just want to do something like:

    my $val = exists $res{ someval } ? $res{ someval } : 0;

    If your "multikeys" are references to hashes, then you would assign { } instead of 0.

Re: Initializing a hash table
by jweed (Chaplain) on Jan 19, 2004 at 22:04 UTC
    Your question is somewhat non-sensical because you dont set hash kets, really, you set values, but I'm going to interpret this question as meaning "How can I have hash values automatically initialized as zero rather than undef?"
    A cursory reading of Tie::Memoize reveals that it looks like what you might want.



    Code is (almost) always untested.
    http://www.justicepoetic.net/