July 08, 2003

Perl Two-Dimensional Hashes

This one's for the search engines...

They say that perl doesn't really support two-dimensional hashes, that it instead supports multi-dimensional hashes, or hashes of hashes, through a reference syntax:

$hash->{dimension1}->{dimension2};

But, it actually does support two-dimensional hashes:

$hash->{"dimension1", "dimension2"};

which, I believe, is deprecated from a bygone era. The question is how to loop through the damn thing - how to even isolate the value of "dimension1" from "dimension2".

foreach my $key (keys %$hash) {
    print $key;    # glommed together
}

That doesn't work. Turns out you need the subscript separator, which is $; . How would you know to look for the definition of the subscript separator? Right. You wouldn't. I lucked out by finding a three-year old article posting on usenet after searching for "2-D Hash". Bleah.

foreach my $key (keys %$hash) {
    my ($dimension1, $dimension2) = 
        (split %;, $key)[0,1];
}
Then you can push them back in a real multidimensional hash at your leisure.

Posted by Curt at July 8, 2003 08:37 PM