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:
Sorting question

 



fig
stranger

Apr 29, 2001, 12:48 PM

Post #1 of 4 (309 views)
Sorting question Can't Post

Why does...


Code
@sortedarray  = sort {$a cmp $b} @unsortedarray;

...produce:

/home/perl/MP3s/Agent Orange
/home/perl/MP3s/Agent Orange/This is the Voice
/home/perl/MP3s/Aphex Twin
/home/perl/MP3s/Aphex Twin/ Selected Ambient Works Volume II - Disc 1
/home/perl/MP3s/Apollo 440
/home/perl/MP3s/Apollo 440/Gettin' High on Your Own Supply
/home/perl/MP3s/armand van helden
/home/perl/MP3s/armand van helden/Sampleslaya Enter The Meatmarket

...instead of:

/home/perl/MP3s/armand van helden
/home/perl/MP3s/armand van helden/Sampleslaya Enter The Meatmarket
/home/perl/MP3s/Agent Orange
/home/perl/MP3s/Agent Orange/This is the Voice
/home/perl/MP3s/Aphex Twin
/home/perl/MP3s/Aphex Twin/ Selected Ambient Works Volume II - Disc 1
/home/perl/MP3s/Apollo 440
/home/perl/MP3s/Apollo 440/Gettin' High on Your Own Supply

As you can see the case is throwing it off. What can I do differently to get around this?

Thanks,
fig



Jasmine
Administrator / Moderator

Apr 29, 2001, 1:39 PM

Post #2 of 4 (308 views)
Re: Sorting question [In reply to] Can't Post

Use:


Code
@sortedarray  = sort {lc $a cmp lc $b} @unsortedarray;

cmp sorts ASCIIbetically, not alphabetically. So when case matters, lc the $a and $b (lc = lower case). It only lc's the elements temporarily for sorting, so the case will be the original case for each element in @sortedarray.



fig
stranger

Apr 29, 2001, 1:45 PM

Post #3 of 4 (307 views)
Re: Sorting question [In reply to] Can't Post

Thanks Jasmine, I really appreciate the assitance.



BigRich
Novice

Apr 29, 2001, 3:13 PM

Post #4 of 4 (305 views)
Re: Sorting question [In reply to] Can't Post

That still won't make "ar" sort before "ag" or "ap", upper or lower case.

If the op wants to have the lower case sorted and placed before the upper case then he'll need something like:

$dir = '/home/perl/MP3s/';

@unsorted = <DATA>;

@sorted_lc = sort grep /^$dir[a-z].+/, @unsorted;
@sorted_uc = sort grep /^$dir[A-Z].+/, @unsorted;

@sorted = (@sorted_lc,@sorted_uc);

for (@sorted) {
print $_,"\n";
}


BigRich


 
 


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

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