简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM