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,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,


In reply to Re: How to bucket a Hash by Athanasius
in thread How to bucket an Hash by techman2006

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.