Training, Open Source computer languages
PerlPHPPythonMySQLApache / TomcatTclRubyJavaC and C++LinuxCSS 
Search for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
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:
@stuff = (
       {"submitted",1010101,"person","George"},
       {"submitted",1020101,"person","Mildred"},
       {"submitted",1010201,"person","Fred"},
       {"submitted",1020102,"person","Ginger"},
       {"submitted",1020201,"person","Tom"},
       {"submitted",1010001,"person","Graham"} );

@newstuff = sort bywhen @stuff;
foreach $pers (@newstuff) {
       print $$pers{person}." at ".$$pers{submitted}."\n";
       }

sub bywhen {
       $$a{submitted} <=> $$b{submitted};
       }


runs to give

Code:
earth-wind-and-fire:~/apr05 grahamellis$ perl phsort
Graham at 1010001
George at 1010101
Fred at 1010201
Mildred at 1020101
Ginger at 1020102
Tom at 1020201
earth-wind-and-fire:~/apr05 grahamellis$


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.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2014: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho