| |||||||||||
| |||||||||||
Sorting a list of hashes Posted by enquirer (enquirer), 14 April 2005 I have an array @responses. Each element of this array is a hash.I want to sort the array depending on an element of the hash, how would I do this? To be a bit more specific; each hash has a 'submitted' key containing a number pertaining to when the response in question was submitted, I want to sort the @responses array based on this value. Does that makes sense? Anyway, I'm sure that this is possible but I'm having some trouble getting my head around the sort function I need to produce, I'd be very grateful if you could offer any help. Posted by admin (Graham Ellis), 14 April 2005 Yes, think it makes sense. Is this similar:Code:
runs to give Code:
The "bywhen" sort subroutine takes inputs $a and $b (they're set by perl within its sort routine which then calls back to it. The idea is that the named routine - bywhen in this example - returns a -ve, 0 or +ve value if $a comes before $b in the sort order required, has the same sort order, or comes after. In the example above, $a and $b - the list elements to be sorted - are references to hashes, thus the $$ notation used. Note that I could have rewritten $$a{submitted} as $a->{submitted} - an alternative syntax that means the same thing. This page is a thread posted to the opentalk forum
at www.opentalk.org.uk and
archived here for reference. To jump to the archive index please
follow this link.
|
| ||||||||||
PH: 01144 1225 708225 • FAX: 01144 1225 793803 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho |