Perl用一组键来哈希 [英] Perl hashes with an array of keys

查看:109
本文介绍了Perl用一组键来哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个包含n个元素(n大于1)的数组,是否有一种优雅的方式来引用散列结构中的元素,其中每个元素都是关键字?



例如:

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

考虑到这个或类似的东西,我想访问以下内容:

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

如果这是一个固定数量的元素,它会很简单,但我不知道在运行时它会有多少肯定不会超过6或7,但否则无法推测)。



我能想到的唯一模式都涉及循环和引用,看起来很笨拙。是否有东西不占用半页或需要Data :: Dumper,如果你有一个打字错误只是为了调试?

解决方案

这就是为什么 Data :: Diver 存在的原因:

 #!/ usr / bin / perl 
使用警告;
使用strict;

使用Data :: Diver qw {Dive};

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

我的@foo = qw(a b z);

print Dive($ hash,@foo);


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

这篇关于Perl用一组键来哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆