作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个想要“unflatten”或“tree-ify”的字符串;也就是说,我想从这个开始:
F=8|A_C=3|A_B=2|D_G_H=11|D_B=2|E=5
{
A => {
B => 2,
C => 3,
},
D => {
B => 2,
G => {
H => 11,
},
},
E => 5,
F => 8,
}
=
分割。登录键/值对:
sub unflatten {
my ($data) = @_;
my @fields = split /\|/, $data;
my $result = {};
for my $datum (@fields) {
my ($key, $value) = split /=/, $datum;
$result->{&processline($key)} = $value;
}
return $result;
}
processline
中尝试了一些递归魔法。功能:
sub processline {
my ($key) = @_;
my ($first, $rest) = split /_/, $key, 2; # split key into at most 2 parts
if($rest) {
return { $first => &processline($rest) };
# if the key is nested, there will be something in $rest
# so recursively process the smaller $rest, and build up the result hashref
}
else {
return $first;
}
}
my $header = "F=8|A_C=3|A_B=2|D_G_H=11|D_B=2|E=5";
use Data::Dumper;
print Dumper &unflatten($header);
$VAR1 = {
'F' => '8',
'HASH(0xe9af60)' => '2',
'HASH(0xe9ae28)' => '11',
'E' => '5',
'HASH(0xe9af90)' => '3',
'HASH(0xe9ae40)' => '2'
};
最佳答案
我相信使用简单的 for
会更直接。循环比使用递归。您选择的方法无法工作,因为它只使用 processline
返回的单个键。分配值,并且不能创建多级哈希。
递归解决方案的工作方式是获取哈希引用、键列表和值,并定义
unflatten($hash, 'key1_key2_key3_key4', 'value')
unflatten($hash->{key1}, 'key2_key3_key4', 'value')`
$hash
它从结果哈希的根开始,并在列表中的每个键之后向前移动一个级别。
sub unflatten {
my $result = {};
for my $item (split /\|/, $_[0]) {
my ($keys, $value) = split /=/, $item;
my @keys = split /_/, $keys;
my $hash = $result;
while (@keys > 1) {
my $key = shift @keys;
$hash->{$key} ||= {};
$hash = $hash->{$key};
}
$hash->{$keys[0]} = $value;
}
return $result;
}
$VAR1 = {
'A' => {
'C' => '3',
'B' => '2'
},
'F' => '8',
'D' => {
'G' => {
'H' => '11'
},
'B' => '2'
},
'E' => '5'
};
use strict;
use warnings;
use Data::Dumper;
my $data = 'F=8|A_C=3|A_B=2|D_G_H=11|D_B=2|E=5';
my $result = {};
unflatten2($result, $_) for split /\|/, $data;
print Dumper $result;
sub unflatten2 {
my ($hash, $data) = @_;
if ($data =~ /_/) {
my ($key, $rest) = split /_/, $data;
unflatten2($hash->{$key} ||= {}, $rest);
}
else {
my ($key, $val) = split /=/, $data;
$hash->{key} = $val;
}
}
Data::Diver
感兴趣模块,它适用于这样的情况,虽然文档有点笨拙
use strict;
use warnings;
use Data::Diver qw/ DiveVal /;
use Data::Dumper;
my $data = 'F=8|A_C=3|A_B=2|D_G_H=11|D_B=2|E=5';
my $result = {};
for (split /\|/, $data) {
my ($keys, $val) = split /=/;
DiveVal($result, split /_/, $keys) = $val;
}
print Dumper $result;
关于perl - 从散列键列表中反序列化嵌套散列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24093567/
我是一名优秀的程序员,十分优秀!