gpt4 book ai didi

Perl:创建散列的散列,最后一个键作为对数组的引用

转载 作者:行者123 更新时间:2023-12-01 12:59:07 25 4
gpt4 key购买 nike

http://codepad.org/8fJG5XaB

需要一些帮助来创建哈希引用的哈希引用,最后一个键作为对数组的引用。

use Data::Dumper;

my $foo = "a:b:c:d:a";
my $bar = "a:b:c:d:z";
my $hoh = {};

sub createHash {

my ($hoh,$orig,$rest,$last) = @_;
$rest = $rest || $orig;
$_ = $rest;

if (/^(.*?):(.*)$/) {
$hoh->{$1} = $hoh->{$1} || {};
createHash($hoh->{$1},$orig,$2,$1);
}
elsif (defined($last)) {
push (@{$hoh->{value}} , [$rest,$orig]);
}

return $hoh;
}

$hoh = createHash($hoh,$foo,undef);
$hoh = createHash($hoh,$bar,undef);

print Dumper($hoh);

需要什么:

$VAR1 = {
'a' => {
'b' => {
'c' => {
'd' => [
[
'a',
'a:b:c:d:a'
],
[
'z',
'a:b:c:d:z'
]
]
}
}
}
};

您可以将其与键盘的输出进行比较。注意细微差别;而不是“d”是具有 arrayref value 的 hashref,“d”是 arrayref 并且没有 value

最佳答案

我建议 Data::Diver ,尽管它有点尴尬,因为它总是想在最后创建标量引用,而这不是我们想要的。因此,我有点作弊。

这里最主要的是我们可以通过一次解密所有 key 并使用 while 循环(在 Data::Diver 内)而不是递归来节省精力(主要是在维护方面)破译起来更有趣 :-) 结合这一事实,即使它是递归的,它也会隐藏在一个漂亮、整洁的函数调用中,这是双赢的:-)

use Data::Dumper;
use Data::Diver qw(DiveRef);

my $foo = "a:b:c:d:a";
my $bar = "a:b:c:d:z";
my $hoh = {};

sub add_item
{
my $href = shift;
my $str = shift;

my @keys = split /:/, $str;

# force an array to be autovivified if it isn't already there.
# (this is kinda cheating)
my $cheat = DiveRef($href, @keys[0..$#keys-1], 0);
my $ref = DiveRef($href, @keys[0..$#keys-1]);

# if we cheated (thus $$cheat will be undef), we need to pop that
# off.
pop @$$ref unless $$cheat;

# store this at the end.
push @{$$ref}, [ $keys[-1], $str ];

return;
}

add_item($hoh, $foo);
add_item($hoh, $bar);
print Dumper($hoh);

希望对你有帮助,

更新:与tye交谈后,他提供了一种更简洁的方法来做到这一点。它使用 Data::Diver仍然,但嵌入了一个更简单的解决方法。 (他声称 perl 在 :lvalue subs 和 push 上有一个错误——我不知道更好,所以我相信他的话。)

use Data::Dumper;
use Data::Diver qw(DiveRef DiveVal);

my $foo = "a:b:c:d:a";
my $bar = "a:b:c:d:z";
my $hoh = {};

sub add_item
{
my $href = shift;
my $str = shift;

my @keys= split /:/, $str;
my $last= pop @keys;
push @{ DiveVal( $href, \( @keys ) ) ||= []}, [ $last, $str ];


return;
}

add_item($hoh, $foo);
add_item($hoh, $bar);
print Dumper($hoh);

关于Perl:创建散列的散列,最后一个键作为对数组的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7746693/

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