我有以下哈希
my %input_hash = (
'test1' => '100',
'test2' => '200',
'test3' => '300',
'test4' => '400',
'test5' => '500'
);
我需要的是从上面的哈希构建哈希哈希。我需要将上面的键值对中的前两个放入哈希哈希的键中。用这个例子更好地解释了。 期望的输出:
my %expected_hash = (
1 => {
'test1' => '100',
'test2' => '200',
},
2 => {
'test3' => '300',
'test4' => '400',
},
3 => {
'test5' => '500'
},
);
我希望分裂是动态的。例如,如果我需要拆分3,则所需的输出应为
my %expected_hash = (
1 => {
'test1' => '100',
'test2' => '200',
'test3' => '300',
},
2 => {
'test4' => '400',
'test5' => '500'
},
);
答案 0 :(得分:4)
这是一个使用splice
来获取动态数量元素的版本。请注意,您必须对散列中的键进行排序,因为散列是无序的。
use strict;
use warnings;
use Data::Dumper;
my %input_hash = (
'test1' => '100',
'test2' => '200',
'test3' => '300',
'test4' => '400',
'test5' => '500',
'test6' => '600',
'test7' => '700',
'test8' => '800',
'test9' => '900'
);
my $foo = foo(\%input_hash, 4);
print Dumper $foo;
sub foo {
my ($href, $count) = @_;
my @keys = sort keys %$href;
my %hash;
my $i = 1;
while (@keys) {
$hash{$i++} = { map { $_ => $href->{$_} }
splice @keys, 0, $count };
}
return \%hash;
}
<强>输出:强>
$VAR1 = {
'1' => {
'test1' => '100',
'test4' => '400',
'test3' => '300',
'test2' => '200'
},
'3' => {
'test9' => '900'
},
'2' => {
'test8' => '800',
'test5' => '500',
'test7' => '700',
'test6' => '600'
}
};
答案 1 :(得分:2)
这是一个解决方案,使用根据%input_hash
中的多个键和$chunk_size
中设置的所需大小构建的索引数组:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
my %input_hash = (
'test1' => '100',
'test2' => '200',
'test3' => '300',
'test4' => '400',
'test5' => '500'
);
my $chunk_size = 2;
my @indexes = map {int($_ / $chunk_size) + 1} 0 .. keys %input_hash;
my %expected_hash;
for my $key (sort keys %input_hash) {
my $index = shift @indexes;
$expected_hash{$index}{$key} = $input_hash{$key};
}
print Dumper \%expected_hash;
输出:
$VAR1 = {
'1' => {
'test1' => '100',
'test2' => '200'
},
'3' => {
'test5' => '500'
},
'2' => {
'test4' => '400',
'test3' => '300'
}
};
当然,正如TLP所提到的,你必须对%input_hash
进行排序才能实现这一目标。
答案 2 :(得分:0)
#! /usr/bin/perl -w
use strict;
my ($expected_hash_key, $cnt, $L1, $L2) = (1, 1, "", "");
my %expected_hash;
# Change $LIMIT to required value. 2 or 3.
my $LIMIT = 2;
my %input_hash = (
'test1' => '100',
'test2' => '200',
'test3' => '300',
'test4' => '400',
'test5' => '500'
);
for (sort keys %input_hash) {
$cnt++;
$expected_hash{$expected_hash_key}{$_} = $input_hash{$_};
if ($cnt == $LIMIT + 1) {
$cnt = 1;
$expected_hash_key++;
}
}
for $L1 (sort keys %expected_hash) {
print "$L1 ==> \n";
for $L2 (sort keys %{ $expected_hash{$L1} }) {
print "$L2 -> $expected_hash{$L1}{$L2}\n";
}
print "\n";
}