in reply to How can I split a hash into other N hashes
Since a hash can be treated as an even sized list/array, you can count the number of elements in the hash and splice the 'array' and generate new hashes.
This requires you do not care for any sorting and simply want to split the array!
(Sample implementation for hashes with an even number of keys, modifying to cope with uneven number of keys is left as an exercise to the reader.)
Sample output:#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %hash = ( a => 1, b => 2, c => 3, d => 4, ); my $keycount = (keys %hash); # hash has 4 keys (and 8 elements) # array index: 0 1 2 3 4 5 6 7 # hash value: a, 1, b, 2, c, 3, d, 4 my %hash1 = splice [ %hash ], 0, $keycount; my %hash2 = splice [ %hash ], $keycount, $keycount; print Dumper \%hash1, \%hash2; exit;
$VAR1 = {
'b' => 2,
'd' => 4
};
$VAR2 = {
'c' => 3,
'a' => 1
};
|
|---|