Linux Perl将散列的一部分保存到新的散列 代码 问题:
在perl中,是否有任何方法可以使用数组/散列来指定键来构建散列引用字符串/标识符 因此,对于上面的代码,我希望从Linux Perl将散列的一部分保存到新的散列 代码 问题:,linux,perl,Linux,Perl,在perl中,是否有任何方法可以使用数组/散列来指定键来构建散列引用字符串/标识符 因此,对于上面的代码,我希望从@arr获取字符串,并使用它们生成字符串 use strict; use warnings; my $hash = { foo => { bar => { baz => "hi" } } }; my @arr = qw/foo bar/;
@arr
获取字符串,并使用它们生成字符串
use strict;
use warnings;
my $hash = {
foo => {
bar => {
baz => "hi"
}
}
};
my @arr = qw/foo bar/;
这只是一个示例,嵌套哈希的数量可能是可变的
尝试 所以我知道如果我知道筑巢的水平,那么我就可以使用
my $newhash = $hash->{'foo'}->{'bar'};
但我似乎想不出一个方法,当筑巢是未知的
额外的
如需更多信息,请询问。您需要遍历哈希树
perl 5.20
@你是怎么发现的?我记得我对这个问题发表了评论,所以我可以通过在搜索中加入我的名字在谷歌上轻松找到它:)@HåkonHægland啊,太酷了,谢谢!
perl 5.20
#!/usr/bin/env perl
# always use these two
use strict;
use warnings;
# use autodie to automatically die on open errors
use autodie;
my $hash = {
foo => {
bar => {
baz => "hi"
}
}
};
my @arr = qw/foo bar/;
my $hash_ref = $hash;
for my $key ( @arr ){
$hash_ref = $hash_ref->{$key};
}
# $hash_ref is now at the end of the array
print Dumper( $hash_ref );