John O John O - 11 months ago 44
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:


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 Source

That's why Data::Diver exists:

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);