简体   繁体   English

Perl使用一系列键进行哈希处理

[英]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? 给定一个包含n个元素(n大于1)的数组,是否有一种优雅的方式来引用哈希结构中的元素,其中每个元素都是序列中的键?

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). 如果这是一个固定数量的元素,那将很简单,但我不知道它在运行时会有多少(当然不会超过6或7,但不可能是不可思议的)。

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? 有什么东西不占用半页或需要Data :: Dumper,如果你有一个错误只是为了调试?

That's why Data::Diver exists: 这就是Data :: Diver存在的原因:

#!/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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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