John O John O - 1 month ago 6
Perl Question

Perl hashes with an array of keys

Given an array which contains n elements (n more than 1), is there an elegant way to refer to the element in a hash structure where each element is the key in sequence?

For example:

my @foo = ('a','b','z');


Given this or something similar, I'd like to access the following:

$hash->{'a'}->{'b'}->{'z'}


If this was a fixed number of elements it would be simple, but I won't know how many it will be at runtime (certainly never more than 6 or 7, but otherwise unguessable).

The only patterns I can think of all involve loops and references and look clumsy. Is there something that doesn't take up a half a page or require Data::Dumper if you have a typo in it just to debug?

Answer

That's why Data::Diver exists:

#!/usr/bin/perl
use warnings;
use strict;

use Data::Diver qw{ Dive };

my $hash = { a => { b => { z => 'HERE' } } };

my @foo = qw( a b z );

print Dive($hash, @foo);
Comments