
Jasmine
Administrator
/ Moderator
Jan 12, 2000, 5:57 AM
Post #2 of 3
(5514 views)
|
Re: How do I sort on multiple keys?
[In reply to]
|
Can't Post
|
|
Donna: 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"; } </pre><HR></BLOCKQUOTE> 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 </pre><HR></BLOCKQUOTE> The above code was adapted from the book "Effective Perl Programming" by Joseph N. Hall with Randal L. Schwartz. Highly recommended!
|