in reply to Re: Grouping an array of hashrefs by similar key values
in thread Grouping an array of hashrefs by similar key values

Yes i already have some code together to perform this function and create a hash of hashes. The problem I have is when I return these results the records are sorted randomly, rather than in the sorted order as they arrived from the database (there's a date column I didn't include in my example, and each item has a date). Consequently I need to sort the hash of hashes in some way and have each record sorted by the value of the 'item_date' key's value.
  • Comment on Re^2: Grouping an array of hashrefs by similar key values

Replies are listed 'Best First'.
Re^3: Grouping an array of hashrefs by similar key values
by kennethk (Abbot) on Jan 29, 2009 at 05:37 UTC

    The result order isn't actually random - it follows a carefully designed algorithm to maximize the efficiency of hash look-ups. The solution to your problem is to use a sorting function to choose the output order. For example, assume your structure was named %hash and your item_date is in epoch time, thus numerically sortable. You could use the code

    sub by_date { return $hash{$a}{item_date} <=> $hash{$b}{item_date}; } for my $key (sort by_date keys %hash) { print "$hash{$key}{item_key} $hash{$key}{item_description}\n" }

    to print out your database keys and descriptions in chronological order. I expect your dates are in a more complex format, and thus require a more complex sorting method. In order for your sorting function to work properly, it should return -1 if $a comes first, 1 if $b comes first and 0 if they are tied. perlop has a few more details.