Perl用一组键来哈希 [英] Perl hashes with an array of keys
问题描述
例如:
my @foo =('a','b','z');
考虑到这个或类似的东西,我想访问以下内容:
$ hash-> {'a'} - > {'b'} - > {'z'}
如果这是一个固定数量的元素,它会很简单,但我不知道在运行时它会有多少肯定不会超过6或7,但否则无法推测)。
我能想到的唯一模式都涉及循环和引用,看起来很笨拙。是否有东西不占用半页或需要Data :: Dumper,如果你有一个打字错误只是为了调试?
#!/ 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屋!