Home: Need a Custom or Prewritten Perl Program?: I need a program that...:
Sorting an array

New User

Jun 14, 2013, 3:23 PM

Views: 6668
Sorting an array


I need some suggestion regarding sorting an array.


#To sort the above array I did
@index=sort{ $arr2[$a] <=> $arr2[$b] } 0 .. $#arr;
print @index;


4 2 1 3 0

But, if I have an array like the following

@arr=((ch1,100), (ch2,20), (ch1,13), (ch2,45), (ch1,1));

How to sort this kind of array (first sort first element and then sort by second element)

Sample output should be,

4 0 2 1 3

Any suggestions, please advise.



Jun 15, 2013, 7:18 AM

Views: 6655
Re: [rkk] Sorting an array

Perl would ignore the parenthesis in your second array. I assume that you intend an array of arrays. Your expected output is not consistent with my interpretation. Here is what I have.

use strict; 
use warnings;
use Readonly;
Readonly::Array my @arr2 =>
['ch1', 100],
['ch2', 20],
['ch1', 13],
['ch2', 45],
['ch1', 1]
my @index = sort { $arr2[$a][0] cmp $arr2[$b][0]
or $arr2[$a][1] <=> $arr2[$b][1]
} 0 .. $#arr2;
print "@index\n";

OUTPUT: 4 2 0 1 3

UPDATE: Please refer to cross posts. This question was already answered on perlmonks
Good Luck,

(This post was edited by BillKSmith on Jun 15, 2013, 7:37 AM)