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

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Advanced:
How do I sort on multiple keys?



Jan 12, 2000, 5:25 AM

Post #1 of 3 (6289 views)
How do I sort on multiple keys? Can't Post

I'm looking to sort on State, then City. Both sets of information are pushed into their own array while reading from the datafile. So technically, my arrays are like this:

@city = ("Orlando", "San Francisco", "Los Angeles", "St. Pete", "Clearwater","etc...");
@states = ("FL", "CA", "CA", "MN", "FL");

I've tried many convoluted ways to do this sort (by state, then by city). Does anyone have an idea?

Any help would be appreciated... thanks!

Administrator / Moderator

Jan 12, 2000, 5:57 AM

Post #2 of 3 (6290 views)
Re: How do I sort on multiple keys? [In reply to] Can't Post


I'm assuming that $state[0] is the state where $city[0] is located, just as $state[26] is the state for $city[26]. If so...

The key is to use the or statement. Consider the following:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

@city = ("Orlando", "San Francisco", "Los Angeles", "St. Pete", "Clearwater");
@states = ("FL", "CA", "CA", "MN", "FL");

@sorted = sort {
$states[$a] cmp $states[$b] or
$city[$a] cmp $city[$b]
} 0 .. $#states;
for (@sorted){
print "$state[$_], $city[$_]\n";

What's happening here is that the expression to the left of the or statement (states) is sorted first, then the expression to the right (city). The above code, when run, yields:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

CA, Los Angeles
CA, San Francisco
FL, Clearwater
FL, Orlando
MN, St. Pete

The above code was adapted from the book "Effective Perl Programming" by Joseph N. Hall with Randal L. Schwartz. Highly recommended!

Enthusiast / Moderator

Jan 12, 2000, 6:03 AM

Post #3 of 3 (6290 views)
Re: How do I sort on multiple keys? [In reply to] Can't Post

Well, that was well put. The only thing else I would have said was that the user should realize you're sorting the INDICES (pl. of "index", just in case...) of the array, not the elements; it's a nice trick. You basically sort the numbers 0 through $x in the order you want them in, and then you can do as Jasmine did:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

@indices = sort { $array[$a] cmp $array[$b] } 0 .. $#array;
for (@indices) {
print $array[$_];

As Jasmine showed, doing this allows you to keep the order of the original array intact, but gives you an array of the NEW indices where the elements would be if you sorted them.

[This message has been edited by japhy (edited 01-12-2000).]


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

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