Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access nested hash in Perl HoH without using keys()?

Consider the following HoH:

$h = {
    a => {
           1 => x
    },
    b => {
           2 => y
    },
    ...
}

Is there a way to check whether a hash key exists on the second nested level without calling keys(%$h)? For example, I want to say something like:

if ( exists($h->{*}->{1}) ) { ...

(I realize you can't use * as a hash key wildcard, but you get the idea...)

I'm trying to avoid using keys() because it will reset the hash iterator and I am iterating over $h in a loop using:

while ( (my ($key, $value) = each %$h) ) {
    ...
}

The closest language construct I could find is the smart match operator (~~) mentioned here (and no mention in the perlref perldoc), but even if ~~ was available in the version of Perl I'm constrained to using (5.8.4), from what I can tell it wouldn't work in this case.

If it can't be done I suppose I'll copy the keys into an array or hash before entering my while loop (which is how I started), but I was hoping to avoid the overhead.

like image 563
MisterEd Avatar asked Mar 17 '26 12:03

MisterEd


2 Answers

Not really. If you need to do that, I think I'd create a merged hash listing all the second level keys (before starting your main loop):

my $h = {
    a => {
           1 => 'x'
    },
    b => {
           2 => 'y'
    },
};

my %all = map { %$_ } values %$h;

Then your exists($h->{*}->{1}) becomes exists($all{1}). Of course, this won't work if you're modifying the second-level hashes inside the loop (unless you update %all appropriately). The code also assumes that all values in $h are hashrefs, but that would be easy to fix if necessary.

like image 167
cjm Avatar answered Mar 19 '26 20:03

cjm


No. each uses the hash's iterator, and you cannot iterate over a hash without using its iterator, not even in the C API. (That means smart match wouldn't help anyway.)

Since each hash has its own iterator, you must be calling keys on the same hash that you are already iterating over using each to run into this problem. Since you have no problem calling keys on that hash, could you just simply use keys instead of each? Or maybe call keys once, store the result, then iterate over the stored keys?

like image 43
ikegami Avatar answered Mar 19 '26 20:03

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!