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: Perl Programming Help: Intermediate:
Sorting array

 



kepler
Novice

Sep 24, 2015, 4:42 PM

Post #1 of 3 (1129 views)
Sorting array Can't Post

Hi,

I'm trying to sort an array in the following manner: here's a sample of the array lines:

1012|01|22|some text...
-100|05|01|other text..
2020|05|07|text...
-2003|11|27|and another...
2020|05|06|text...

I want to sort numerically first by the first row, then the seconda and the third, so I would get:

-2003|11|27|and another...
-100|05|01|other text..
1012|01|22|some text...
2020|05|06|text...
2020|05|07|text...

Any ideas are welcome.

Cheers,

Kepler


BillKSmith
Veteran

Sep 24, 2015, 6:53 PM

Post #2 of 3 (1126 views)
Re: [kepler] Sorting array [In reply to] Can't Post

Refer to FAQ

Code
perldoc -q "how do I sort an array"

Use the Schwartzian transformation.

Code
use strict; 
use warnings;
use Data::Dumper;
my @in_array = (
'1012|01|22|some text...',
'-100|05|01|other text..',
'2020|05|07|text...',
'-2003|11|27|and another...',
'2020|05|06|text...',
);

my @sorted_array = map {$_->[0]}
sort {$a->[1]<=>$b->[1] or $a->[2]<=>$b->[2] or $a->[3]<=>$b->[3]}
map {[$_,split(/\|/, $_)]} @in_array;


$" = "\n";
print "@sorted_array\n";


Output:

Code
-2003|11|27|and another... 
-100|05|01|other text..
1012|01|22|some text...
2020|05|06|text...
2020|05|07|text...

Good Luck,
Bill

(This post was edited by BillKSmith on Sep 24, 2015, 7:35 PM)


kepler
Novice

Sep 25, 2015, 12:03 AM

Post #3 of 3 (1120 views)
Re: [BillKSmith] Sorting array [In reply to] Can't Post

Good morning Bill,

This is a great answer :) It will solve further problems I might have in sorting data.The logic is rather simple - but I was not aware.

Thank you very much,

Kepler

 
 


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

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