I am trying to write a Perl subroutine to process any given hash (passed by reference) but I would like to make it a generic one so that I can use it anywhere.
Assuming the hash has simple key/value pairs and is not an elaborated record (containing arrays of arrays or arrays of hashes), is there any way to find how deep the hash of hashes runs?
For example
my %stat = (
1 => { one => "One is one.", two => "two is two"},
2 => { one => "second val wone", two => "Seconv v"}
);
The hash above has first level key 1
which has two keys one
and two
. So it is a hash with two levels.
My question is whether is there any way to test and find this information that the hash has two levels?
About the "problem that has led me to believe that I need to know the depth that a Perl hash is nested". Here is my situation.
The program is creating a data structure of three levels, and also publishing it in a text file for other scripts which are processing this published data and doing something else.
The program is also reading and hashing other data structures of five levels, which has data related to the hash in the first point.
The program is also processing a continuously growing log file and collecting data.
Traversing hash values and tracking levels could give answer,
use strict;
use warnings;
use v5.16;
{ my $max;
sub hlevel {
my ($h, $n) = @_;
$max = 0 if !$n;
$max = $n if $max < $n;
__SUB__->($_, $n +1) for grep {ref eq "HASH"} values %$h;
return $max;
}}
my %h;
$h{a}{b}{c}{d}{e} =1;
$h{a}{b}{c}{d}{e1}{f} =1;
$h{a}{b}{c}{d}{e1}{f1}{g} =1;
print hlevel(\%h, 0);
output
6