Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: sorting in hashes

by Util (Priest)
on Aug 22, 2009 at 16:32 UTC ( [id://790587]=note: print w/replies, xml ) Need Help??


in reply to sorting in hashes

Assuming that I have guessed correctly at the structure of your missing example data, this solves the problem.
#!/usr/bin/perl use strict; use warnings; my %institute_department_roll_name_mark_HoHoHoH = ( CIA => { HUMINT => { rollno1 => { Bob => 65, Adam => 87, }, rollno2 => { Dennis => 37, Arthur => 41, }, }, SIGINT => { rollno1 => { Harry => 87, Albus => 100, }, rollno2 => { M => 70, Q => 98, James => 75, }, }, }, NSA => { Encryption => { rollno1 => { Abel => 13, Baker => 28, Charlie => 57, }, rollno2 => { Roger => 2, Fox => 3, Dog => 2, }, }, Decryption => { rollno1 => { Marin => 62, Chong => 66, }, rollno2 => { Dave => 0, }, }, }, ); # Create a flattened data structure. my $h1 = \%institute_department_roll_name_mark_HoHoHoH; my @institute_department_roll_name_mark_AoH; while ( my ( $institute, $h2 ) = each %{$h1} ) { while ( my ( $department, $h3 ) = each %{$h2} ) { while ( my ( $roll, $h4 ) = each %{$h3} ) { while ( my ( $name, $mark ) = each %{$h4} ) { push @institute_department_roll_name_mark_AoH, { INST => $institute, DEPT => $department, ROLL => $roll, NAME => $name, MARK => $mark, }; } } } } @institute_department_roll_name_mark_AoH = sort { $b->{MARK} <=> $a->{MARK} or $a->{INST} cmp $b->{INST} or $a->{DEPT} cmp $b->{DEPT} or $a->{ROLL} cmp $b->{ROLL} or $a->{NAME} cmp $b->{NAME} } @institute_department_roll_name_mark_AoH; for my $href (@institute_department_roll_name_mark_AoH) { printf "%7d\t%-7s\t%-15s\t%-7s\t%s\n", @{$href}{qw( MARK INST DEPT ROLL NAME )}; }
Output:
100 CIA SIGINT rollno1 Albus 98 CIA SIGINT rollno2 Q 87 CIA HUMINT rollno1 Adam 87 CIA SIGINT rollno1 Harry 75 CIA SIGINT rollno2 James 70 CIA SIGINT rollno2 M 66 NSA Decryption rollno1 Chong 65 CIA HUMINT rollno1 Bob 62 NSA Decryption rollno1 Marin 57 NSA Encryption rollno1 Charlie 41 CIA HUMINT rollno2 Arthur 37 CIA HUMINT rollno2 Dennis 28 NSA Encryption rollno1 Baker 13 NSA Encryption rollno1 Abel 3 NSA Encryption rollno2 Fox 2 NSA Encryption rollno2 Dog 2 NSA Encryption rollno2 Roger 0 NSA Decryption rollno2 Dave

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://790587]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (3)
As of 2024-04-19 21:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found