gpt4 book ai didi

linux - Perl 将一段哈希值保存到一个新的哈希值中

转载 作者:太空宇宙 更新时间:2023-11-04 04:55:06 24 4
gpt4 key购买 nike

代码

use strict;
use warnings;

my $hash = {
foo => {
bar => {
baz => "hi"
}
}
};

my @arr = qw/foo bar/;
<小时/>

问题

perl 中是否有任何方法可以使用数组/散列来构建散列引用字符串/标识符来指定键?

因此,通过上面的代码,我想从 @arr 获取字符串并使用它们生成字符串

my $newhash = $hash->{'foo'}->{'bar'};

这只是一个示例,嵌套哈希的数量可以是可变的

<小时/>

尝试过

所以我知道如果我知道嵌套的级别那么我就可以使用

my $newhash = { map { $_ => $hash->{$_} } qw/some values/ };

但是当嵌套未知时我似乎想不出办法。

额外

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

关于linux - Perl 将一段哈希值保存到一个新的哈希值中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49254934/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com