• Status: Solved
• Priority: Medium
• Security: Public
• Views: 245

# Sorting on multiple fields

I have the O'Reily Programming Perl book (2nd Ed.) that has sample code for sorting on multiple fields.  The example is on page 218.  I'll include the example here too.

sub prospects {
\$money{\$b} <=> \$money{\$a}
or
\$height{\$b} <=> \$height{\$a}
or
\$age{\$a} <=> \$age{\$b}
or
\$lastname{\$a} <=> \$lastname{\$b}
or
\$a cmp \$b;
}
@sortedclass = sort prospects @class;

I understand what this code is supposed to do but I can't figure out the format of the data.  Can someone explain what @class looks like.  Is it some kind of array of hash tables?

I need to sort a set of records based on multiple fields and print out the list of records in order.  Any help with this would be appreciated.
0
1 Solution

Commented:
@class=qw(aa bb cc dd ee ff);
@money{@class}=(22,22,22,11,11,11);
@height{@class}=(150,150,160,160,150,160);
@age{@class}=(9,10,9,10,9,10);
@lastname{@class}=(1,2,3,1,2,3);  #are you sure this is numeric?
0

Commented:
@class is just an array of name of persons or any datastructure that refers to the persons.
@class = qw(john marry);
or
@class = qw(\$a \$b);
Then there are different hashes which has above array elements as there keys and they have some assigned values which are used in sorting..

I checked the book and lastname comparision uses "cmp"
operator..

person,money,height,age,lastname
A,300,165,25,smith
B,200,170,30,brown
C,400,110,12,williams

in a file "in.txt";
-------------------------------------
open IN, "in.txt";
@lines = <IN>;
shift @lines;  #to remove first line..
----------------------------------------

Now You have complete data in @lines.
You can create the hashes
say
-----------------------------------
foreach (@lines){
@values = split /\,/;
\$person = shift @values;
(\$money{\$person},\$height{\$person},\$age{\$person},\$lastname{\$person}) = @values;
push @class, \$person;
}
------------------------------
Now you can use the subroutine that is provided in the book.
------------------------------------
@sortedclass = sort prospects @class
----------------------------------------

To Print the records
====================
------------------------------------------
foreach \$person (@sortedclass){
print "\$person,\$money{\$person},\$height{\$person},\$age{\$person},\$lastname{\$person}\n";
}
-------------------------------------------------

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.