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: Beginner:
numeric sorting

 



aland
New User

Mar 21, 2010, 8:13 AM

Post #1 of 5 (854 views)
numeric sorting Can't Post

Hi guys, I have a script that goes through files labelled 1-12.I need to keep them in order.But instead perl takes the files in order of 1,10,11,12,2,3,4,5...

so i wrote the code below:

Code
 
my @openfiles = <*.a> #as in match all the files in the directory labelled 1.a, 2.a,3.a etc
my @filearray = [@openfiles] #as in put these files into a list
my @sortfiles = sort {$a <=> $b} @filearray
my @files = (@sortfiles)

then the next bit is just foreach...and continue on with my script that works....

But it doesnt work, any ideas?Im not using strict or warnings?
Thanks


FishMonger
Veteran / Moderator

Mar 21, 2010, 8:39 AM

Post #2 of 5 (850 views)
Re: [aland] numeric sorting [In reply to] Can't Post

Why are you not using strict and warnings?

Why are doing this:

Code
my @filearray = [@openfiles]


Why are you copying your list to multiple arrays?

Why are you doing a numerical comparison on a string?


7stud
Enthusiast

Mar 21, 2010, 3:44 PM

Post #3 of 5 (845 views)
Re: [aland] numeric sorting [In reply to] Can't Post


Code
use strict; 
use warnings;
use 5.010;

my @file_names = (
'1.a',
'10.a',
'11.a',
'12.a',
'2.a',
'3.a',
'4.a',
'5.a',
);

my @sorted_file_names
= sort {substr($a, 0, -2) <=> substr($b, 0, -2)} @file_names;

say for @sorted_file_names;

--output:--
1.a
2.a
3.a
4.a
5.a
10.a
11.a
12.a



(This post was edited by 7stud on Mar 21, 2010, 3:57 PM)


murugaperumal
Novice


Mar 21, 2010, 8:50 PM

Post #4 of 5 (839 views)
Re: [aland] numeric sorting [In reply to] Can't Post


Code
use Data::Dumper; 
my @files=<*.a>;
print Dumper \@files;
my @sortfile=sort {$a <=> $b} @files;
print Dumper \@sortfile;



aland
New User

Mar 22, 2010, 4:21 AM

Post #5 of 5 (827 views)
Re: numeric sorting [In reply to] Can't Post

Thanks a million lads,that helped so much.

 
 


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

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