User Control Panel
Advertisements

HELP US, HELP YOU!

sorting an array of hashes

 
Post new topic   Reply to topic    Bot Depot Forum Index -> Perl
View unanswered posts
Author Message
malefactor
Member
Member


Joined: 27 Jan 2005
Posts: 109
Location: Lewiston, ME
Reputation: 17.7Reputation: 17.7

PostPosted: Wed Jun 29, 2005 1:37 am    Post subject: sorting an array of hashes Reply with quote

anyone know where I can get a function to sort an array of hashes?
Back to top
darkmonkey
The Merovingian
The Merovingian


Joined: 18 Apr 2004
Posts: 2557
Location: London, England
Reputation: 39.3Reputation: 39.3Reputation: 39.3Reputation: 39.3
votes: 7

PostPosted: Wed Jun 29, 2005 9:42 am    Post subject: Reply with quote

sort(keys %{$hash->{value}});
_________________
~ Josh
[ Need bot hosting on a dedicated server? PM me. ]
Back to top
Mojave
Almost An Agent
Almost An Agent


Joined: 01 Nov 2003
Posts: 1434

Reputation: 66.4

PostPosted: Wed Jun 29, 2005 11:19 pm    Post subject: Reply with quote

darkmonkey, what you have is wrong, it's a hash of hashes, not an array of hashes as he asked.

An array of hashes really has to be an array of hash references, since arrays can only store scalars. For a simple sort, you'll need to pick a key in the hash to sort on (although, you can do very complicated sorts if you want). Depending on what the type of the field is (string or number), you use different operators. So, for a string, you would use something like:

my @sorted = sort { $a->{'key'} cmp $b->{'key'} } @array;

For a numeric sort:

my @sorted = sort { $a->{'key'} <=> $b->{'key'} } @array;

$a and $b are elements in the array, which in this case are hash references. You can switch the order of $a and $b to do a reverse sort.
Back to top
malefactor
Member
Member


Joined: 27 Jan 2005
Posts: 109
Location: Lewiston, ME
Reputation: 17.7Reputation: 17.7

PostPosted: Wed Jul 06, 2005 1:39 pm    Post subject: Reply with quote

kewl, I had no idea it could be done that way.

thanks
Back to top
Display posts from previous:   
Post new topic   Reply to topic    Bot Depot Forum Index -> Perl All times are GMT
Page 1 of 1

 



Protected by phpBB Security phpBB-TweakS
phpBB Security Has Blocked 9 Exploit Attempts.
Antispam Captcha Mod by phpbb-security.com
Powered by phpBB © 2001, 2005 phpBB Group