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

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

 



rkk
New User

Jun 14, 2013, 3:23 PM

Post #1 of 2 (2883 views)
Sorting an array Can't Post

Hello,

I need some suggestion regarding sorting an array.

Ex:


@arr=(100,20,3,45,1);
#To sort the above array I did
@index=sort{ $arr2[$a] <=> $arr2[$b] } 0 .. $#arr;
print @index;

Output:

4 2 1 3 0

[download]
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.

Thanks,


BillKSmith
Veteran

Jun 15, 2013, 7:18 AM

Post #2 of 2 (2870 views)
Re: [rkk] Sorting an array [In reply to] Can't Post

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.


Code
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,
Bill

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

 
 


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

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