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

In my new consulting position, I've had to take up coding again as part of my Testing Analyst role. I'm also pretty new to Perl. I'm finding I love the language, but I'm occasionally confused by the multiple ways there are to do most things.

What I am looking for is the easiest/best way to know how many keys there are in the nth dimension of a multidimensional hash. (ie $hash{x}{y}).

For example, I'm using a 2D hash where I have the key to the first dimension, but I want a count of the number of "records" that exist for the 2nd dimension. And then return the value of a specific "record".
  • Comment on Retrieving data from multidimensional hashes

Replies are listed 'Best First'.
Re: Retrieving data from multidimensional hashes
by friedo (Prior) on Aug 11, 2008 at 18:54 UTC
    A couple of options, depending on what appeals to you:
    my $num = keys %{ $hash{key} }; # or my $ref = $hash{key}; my $num = keys %$ref;
    The first one is short-hand for accessing the second-level hash directly, though I find it a tad ugly, especially if the structures get deeper than two levels. The second one grabs the reference for the second level hash and then calls keys on that, which is a bit more explicit.
Re: Retrieving data from multidimensional hashes
by ikegami (Patriarch) on Aug 11, 2008 at 19:13 UTC

    If you can't handle multiple levels, do it level by level.

    my $subhash = $hash{$x}; my $count = keys %$subhash;
      ok, maybe it has been too long since I last wrote code ;) Whats the "my" all about in front of the variables on those lines? Is it just to say "this is a variable name"?

        It's a scoping mechanism and a typo avoidance mechanism.

        Make sure to use use strict; in your programs and modules.

Re: Retrieving data from multidimensional hashes
by eosbuddy (Scribe) on Aug 11, 2008 at 19:06 UTC
    Please checkout this node: http://www.perlmonks.org/?node_id=626183 Also:
    use strict; use warnings; use Data::Dumper; print Dumper(%hash);
    will print out the whole tree view of the hash.