Gossamer Forum
Home : General : Perl Programming :

sorting multiple arrays

Quote Reply
sorting multiple arrays
Is this the best way to sort these arrays or is there a more efficient way.
Code:
my @page = (24,75,41,9);
my @something = (1,2,3,4);
my @text = ("bbbb","aaaa","dddd","cccc ccc");
for (sort { $text[$a] cmp $text[$b] } 0..$#text) {
print "$text[$_]:$page[$_]:$something[$_]\n";
}
This is only an example the arrays I want to sort each have 250 elements.

Thanks
Bob
http://totallyfreeads.com.au
Quote Reply
Re: [lanerj] sorting multiple arrays In reply to
You are only sorting one array there, you know?

Last edited by:

Paul: Jun 1, 2003, 8:05 AM
Quote Reply
Re: [Paul] sorting multiple arrays In reply to
No the 3 arrays sort, try it. They all sort according to @text.
The thing works, I just want to know if there is a more efficient method.

Bob
http://totallyfreeads.com.au
Quote Reply
Re: [lanerj] sorting multiple arrays In reply to
It won't sort properly. You are using "cmp" which is for sorting strings, but two of your arrays are numeric meaning you'd need "<=>"

Using your code, the "page" array sorts as:

75 24 9 41

...so that's not sorted. The "something" array sorts as:

2 1 4 3

...so that's not sorted. The only one that sorts (as expected) is the "text" array:

aaaa bbbb cccc ccc dddd
Quote Reply
Re: [Paul] sorting multiple arrays In reply to
No thats the way there meant to sort, thats the relation between the arrays.
@text is sorted alphabetically and the other arrays sort accordingly.
the output looks like this -
aaaa:75:2
bbbb:24:1
cccc ccc:9:4
dddd:41:3
which is correct.
I just found a good short tute on sorting here http://perlmonks.thepen.com/128722.html
the one I need is the index sort.

Bob
http://totallyfreeads.com.au
Quote Reply
Re: [lanerj] sorting multiple arrays In reply to
Ok so really you aren't sorting multiple arrays, you are sorting one array and grabbing the corresponding element from the other two arrays.
Quote Reply
Re: [Paul] sorting multiple arrays In reply to
Yep, sorry for the confusion.

Bob
http://totallyfreeads.com.au

Last edited by:

lanerj: Jun 1, 2003, 8:57 AM