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

Your best bet would be to use a hash for your root element, keyed on item_key, and then populate it by crawling over your list, adding base elements if the key doesn't exist yet and pushing your actions onto the appropriate array if it does. Details on dealing with hashes of hashes (HoH) and their friends can be found in perllol (and if you need it, basic dereferencing is here). Happy to help debug once you've cobbled some code together.
  • Comment on Re: Grouping an array of hashrefs by similar key values

Replies are listed 'Best First'.
Re^2: Grouping an array of hashrefs by similar key values
by perldj (Initiate) on Jan 28, 2009 at 23:49 UTC
    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.

      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.