How do I know if a Perl hash is multidimensional?

Assuming I have a hash, for example:

$hash_ref = {

  'hashes' => {
    'h1' => { 'klf' => '1', 'moomooland' => '1' },
    'h2' => { 'klf' => '2', 'moomooland' => '2' },
    'h3' => { 'klf' => '3', 'moomooland' => '3' }
  },

  'keys' => {
    'k1' => 'key1',
    'k2' => 'key2',
    'k3' => 'key3'
  }

}

How can I find out as easy as possible that it hashescontains 3 more hashes and keyscontains 3 key / value pairs?

refwill return HASHfor both of them, and I'm not sure if it is possible to find out the depth of these hashes.

Thank:)

+5
source share
3 answers

If you just need to know if the hash is multidimensional, you can iterate over its values ​​and stop if the link is found:

my $is_multi_dimensional = 0;

for my $value (values %$hash_ref) {
    if ('HASH' eq ref $value) {
        $is_multi_dimensional = 1;
        last;
    }
}

or you can use the function each():

while (my (undef, $value) = each %$hash_ref) {
    if ('HASH' eq ref $value) {
        $is_multi_dimensional = 1;
        last;
    }
}
+5
source

You can firstalso grepfor this:

use List::Util 'first';
say 'is multi-dimensional' if first { ref } values %$hash_ref;

# explicitly check for HASH ref this time
my $how_many_md_hashes = grep { 'HASH' eq ref } values %$hash_ref;

NB. first ( List::Util ) , , , .

/I3az/

+5

You can try this to find out the depth of the Perl hash:

#!/usr/bin/perl
use strict;
my $hash_ref = {

  'hashes' => {
    'h1' => { 'klf' => '1', 'moomooland' => '1' },
    'h2' => { 'klf' => '2', 'moomooland' => '2' },
    'h3' => { 'klf' => '3', 'moomooland' => '3' }
  },

  'keys' => {
    'k1' => 'key1',
    'k2' => 'key2',
    'k3' => 'key3'
  }

};
print_nested_hash($hash_ref, 0);

sub print_nested_hash {
    my $hash_ref = shift;
    my $depth = shift;
    foreach my $key (sort keys %{$hash_ref}) {
        print '    ' x $depth, $key, "\n";

        if (ref($hash_ref->{$key}) eq "HASH") {
            print_nested_hash($hash_ref->{$key}, $depth+1);
        }
    }
} 

CONCLUSION:

hashes
    h1
        klf
        moomooland
    h2
        klf
        moomooland
    h3
        klf
        moomooland
keys
    k1
    k2
    k3
+1
source

All Articles