Forum Moderators: coopster & phranque

Message Too Old, No Replies

Sorting Arrays

Array in Array sort

         

Phoog

4:41 pm on Dec 26, 2005 (gmt 0)

10+ Year Member



Hello, I have some problems with array and sorting...

What I Have:
One array with arrays in it, like:
@my_array = (
[10, "Adam", "www.adamhomepage.com"],
[8, "Bill", "www.billhomepage.com"],
[9, "Phil", "www.philhomepage.com"],
[22, "Chris", "www.chrishomepage.com"],
);

Now I want to sort them by the first number so I get:
22, "Chris", "www.chrishomepage.com"
10, "Adam", "www.adamhomepage.com"
9, "Phil", "www.philhomepage.com"
8, "Bill", "www.billhomepage.com"

How do I do that?

Phoog

9:06 pm on Dec 26, 2005 (gmt 0)

10+ Year Member



Hmm, another problem now...

I have:
@result = (
{
points => 10,
name => "bill",
},
{
points => 19,
name => "phil",
},
{
points => 9,
name => "dill",
},
);

And I want to order them by their points... how to?

Thanks...

DrDoc

3:45 am on Dec 27, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



All sorting in Perl is done using the traditional bubble technique.

@sorted = sort { *** } @notsorted;

*** can be any expression you can think of (sort of) where $a is the first value and $b is the second.

So, for example:

Numerical:
@sorted = sort { $a <=> $b } @notsorted;
Alphabetical sort:
@sorted = sort { lc($a) cmp lc($b) } @notsorted;
Alphabetical sort, reversed:
@sorted = sort { lc($b) cmp lc($a) } @notsorted;

In your case you are not just sorting an array ... you are sorting a multidimensional array based on the children.

So, the first case:
@sorted = sort { $b[0] <=> $a[0] } @notsorted;
Literally: "sort based on the first element in the child array, numerically, reversed"

The second case is similar:
@sorted = sort { $b{'points'} <=> $a{'points'} } @notsorted;