CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate: Re: [PapaGeek] Can SPLICE be used to sort an array of hash references?: Edit Log



Kenosis
User

Feb 22, 2014, 9:19 PM


Views: 4539
Re: [PapaGeek] Can SPLICE be used to sort an array of hash references?

Add the following sub:

Code
sub SortHashArray { 
my ( $arrRef, $col ) = @_;
exists $$arrRef[0]->{$col} or die "The key '$col' doesn't exist!\n";
@$arrRef = sort { $b->{$col} <=> $a->{$col} } @$arrRef;
}

And then call it right after the last insertHash():

Code
... 
insertHash(12, 15, 37, 16, 24, "OAKIX");

SortHashArray( \@hashArray, 'p3m' );


Note that the subroutine is sent a reference to the AoH that you want sorted, since it's better not (and unnecessary) to copy the entire AoH for the sort.

I'm sure you notice that the anonymous sub after sort dereferences the reference passed to it, and uses the value of $col as the key to the hash value.

Also placed a line to check whether the col (key) sent exists. If not, the script will die instead if throwing errors during each sort comparison.

Sorted on p3m output:

Code
The final array of hash references has 6 items 
p1y=48 p3m=15 p3y=25 p5y=25 p6m=19 r1y=0 r3m=0 r3y=0 r5y=0 r6m=0 rank=0 ticker=PPCIX
p1y=43 p3m=14 p3y=20 p5y=26 p6m=19 r1y=0 r3m=0 r3y=0 r5y=0 r6m=0 rank=0 ticker=PSSIX
p1y=44 p3m=13 p3y=23 p5y=30 p6m=17 r1y=0 r3m=0 r3y=0 r5y=0 r6m=0 rank=0 ticker=FSCRX
p1y=37 p3m=12 p3y=16 p5y=24 p6m=15 r1y=0 r3m=0 r3y=0 r5y=0 r6m=0 rank=0 ticker=OAKIX
p1y=32 p3m=11 p3y=17 p5y=21 p6m=13 r1y=0 r3m=0 r3y=0 r5y=0 r6m=0 rank=0 ticker=NSEIX
p1y=39 p3m=10 p3y=18 p5y=22 p6m=14 r1y=0 r3m=0 r3y=0 r5y=0 r6m=0 rank=0 ticker=POGRX


Hope this helps!


(This post was edited by Kenosis on Feb 22, 2014, 9:35 PM)


Edit Log:
Post edited by Kenosis (User) on Feb 22, 2014, 9:21 PM
Post edited by Kenosis (User) on Feb 22, 2014, 9:22 PM
Post edited by Kenosis (User) on Feb 22, 2014, 9:23 PM
Post edited by Kenosis (User) on Feb 22, 2014, 9:25 PM
Post edited by Kenosis (User) on Feb 22, 2014, 9:26 PM
Post edited by Kenosis (User) on Feb 22, 2014, 9:30 PM
Post edited by Kenosis (User) on Feb 22, 2014, 9:35 PM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives