Search code examples
perlhashperl-data-structures

How to iterate through Hash (of Hashes) in Perl?


I have Hash where values of keys are other Hashes.

Example: {'key' => {'key2' => {'key3' => 'value'}}}

How can I iterate through this structure?


Solution

  • Is this what you want? (untested)

    sub for_hash {
        my ($hash, $fn) = @_;
        while (my ($key, $value) = each %$hash) {
            if ('HASH' eq ref $value) {
                for_hash $value, $fn;
            }
            else {
                $fn->($value);
            }
        }
    }
    
    my $example = {'key' => {'key2' => {'key3' => 'value'}}};
    for_hash $example, sub {
        my ($value) = @_;
        # Do something with $value...
    };