Hello techman2006,
Your question implies that the code shown works correctly. But what happens if you have an odd number of elements in the hash? Running your code with %hash = ( 1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd', 5 => 'e' ) I get:
16:51 >perl 786_SoPW.pl
Total keys are 5
$VAR1 = {
'1' => 'a',
'5' => 'e'
};
$VAR1 = {
'4' => 'd',
'3' => 'c'
};
$VAR1 = [
{
'1' => 'a',
'5' => 'e'
},
{
'4' => 'd',
'3' => 'c'
}
];
16:51 >
which shows that the fifth element is left out altogether.
Anyway, here is my solution, a variation on hdb’s approach which uses the natatime function from List::MoreUtils:
#! perl
use strict;
use warnings;
use Data::Dump qw( pp );
use List::MoreUtils qw( natatime );
my $i = 1;
my %hash = map { $i++ => $_ } 'a' .. 'e';
print 'Initial hash: ', pp(\%hash), "\n";
my $it = natatime 2, sort { $a <=> $b } keys %hash;
my @array_of_hashes;
while (my @keys = $it->())
{
my %new_hash = map { ( $_, $hash{$_} ) } @keys;
push @array_of_hashes, \%new_hash;
}
print 'Array of hashes: ', pp(\@array_of_hashes), "\n";
Update: Changed 'a' .. 'j' to 'a' .. 'e', and the first argument to natatime from 4 to 2, to match the output shown.
Output:
16:54 >perl 786_SoPW.pl
Initial hash: { 1 => "a", 2 => "b", 3 => "c", 4 => "d", 5 => "e" }
Array of hashes: [{ 1 => "a", 2 => "b" }, { 3 => "c", 4 => "d" }, { 5
+=> "e" }]
16:55 >
Hope that helps,
|