将哈希分成多个哈希值

时间:2014-12-10 14:50:42

标签: perl loops hash splice

如果我有哈希,我怎么能打破"打破"它/"分裂"它分为多个包含相同数量键的哈希? 基本上,数组中的拼接似乎接近我所需要的(循环/切片),但这仅适用于数组。 那么最好的方法是什么呢? 更新
或者最多删除X个键值的方法,以便模拟阵列的拼接 更新

{ foo => 1, bar => 2, bla =>3}  

   { foo => 1 }, { bar => 2 }, { bla => 3 }  if X = 1 
or { foo => 1, bar => 2 }, { bla => 3 }      if X = 2  
or { foo => 1, bar => 2, bla => 3 }          if X = 3 

2 个答案:

答案 0 :(得分:2)

这应该做你想要的。在5.20+上,您可以使用新的切片语法来简化代码。

#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;

sub split_hash {
    my ($x, $hash) = @_;
    my @hashes;
    while (%$hash) {
        my @k = keys %$hash;
        push @hashes, { map each %$hash, 1 .. $x };
        delete @{ $hash }{ keys %{ $hashes[-1] } };
    }
    return @hashes
}

print Dumper([ split_hash($_, { foo => 1,
                                bar => 2,
                                bla => 3,
                              }
            )]) for 1 .. 3;

请注意,编写后,代码会删除原始哈希值。

答案 1 :(得分:1)

与@choroba提供的解决方案类似,但使用splice,并且不会修改传递的哈希:

use Data::Dumper;

use strict;
use warnings;

sub split_hash {

    my ( $x, $hash ) = @_;

    my @keys = keys %$hash;
    my @hashes;

    while ( my @subset = splice( @keys, 0, $x ) ) {

        push @hashes, { map { $_ => $hash->{$_} } @subset };

    }

    return \@hashes;
}


print Dumper( [
        split_hash(
            $_,
            {
                foo => 1,
                bar => 2,
                bla => 3,
            } ) ] ) for 1 .. 3;
相关问题