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

I have some legacy code with a hash in the form $hash{$key1, $key2} which looks like a deprecated form of a 2D hash from searching the internet. Can anybody confirm this? Or is it some kind of slice? The code also uses another old method, dbmopen to save the data. The PODs from CPAN indicate that the interfaces (MLDBM, Berkeley, etc) are not very reliable for saving n-D hashes. Does anybody know a reliable way? Thanks Mike

Replies are listed 'Best First'.
Re: old 2D hash construct
by rodion (Chaplain) on Jul 30, 2006 at 18:35 UTC
    You're right about the 2D hash mechanism, and right that a HoH should be used instead, in general.

    in the section on "$;" (or "$SUBSEP" in english) in perlvar it says

    If you refer to a hash element as

    $foo{$a,$b,$c}

    it really means

    $foo{join($;, $a, $b, $c)}

    The place where it's still useful is if you are storing the hash in a database, and it sounds like your legacy code might be doing this. The caution is that you can't have data the same as the separator, so binary data needs to be escaped in some way.

    Personally, I would change these the form to ' $hash{$key1 . $; . $key2}' to let people know what was going on a little better.

Re: old 2D hash construct
by dirving (Friar) on Jul 30, 2006 at 19:14 UTC
    If all you need to do is save the hashes and then re-load them at a later time you can use the Storable module (which is a core module in recent perls) to serialize them and re-load them quickly and reliably. This is only really necessary if you end up re-writing the code to use the more modern style of 2D hash, because the hash you have there is really just a 1-dimensional hash with a key composed of multiple elements and the DBM modules should be able to store that just fine.
Re: old 2D hash construct
by sweetblood (Prior) on Jul 30, 2006 at 18:10 UTC
    Check out perldoc perldsc

    That's what I do when having trouble getting my head around any perl data structure.

    HTH

    Sweetblood

Re: old 2D hash construct
by planetscape (Chancellor) on Jul 31, 2006 at 11:17 UTC