Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sort help 1

Status
Not open for further replies.

JimJx

Technical User
Joined
Feb 16, 2001
Messages
202
Location
US
Hi all,

I have several directories (~100) that I need to sort and throw into a select box. That I can do except the sort.

The dirs are named the same, except for a number at the end.

Example A1 A2 A3 ... A100

So, you know how the sort works, and I get A1 A10 A100 A2 A20 etc.

How do I get this into a more 'normal' orser so I get A1 A2 A3 ... A100

The code I am working with is:

Code:
@dir = sort {$a<=>$b} (@alf);
foreach $item (@alf)
{
    if (-d "$tree$item" &&!(-l "$tree$item"))
    {
    	next if ($item =~ m/^\.+$/);
        push @dir, $item;
    }
}
print "Directories: @dir\n";

Thanks for any help,
Jim
 
First of all, <=> is for numbers. Since your directories have an "A" on them, you'd want to use cmp.

Code:
@dir = sort { $a cmp $b } @alf;

# or better
@dir = sort { lc($a) cmp lc($b) } @alf;
 
You could use a Schwartzian Transform to sort the mixed data strings how you want. If the directories really were named liked you posted here is an example:

Code:
my @alf = qw(A1 B5 D66 A100 A3 A2 B5 B3 A22);

my @sorted = map  {$_->[0]}
             sort {$a->[1] cmp $b->[1] ||
                   $a->[2] <=> $b->[2]}
             map  {m/^([a-z]+)(\d+)$/i; [$_,lc($1),$2]} @alf;

print "$_\n" for @sorted;

prints:

A1
A2
A3
A22
A100
B3
B5
B5
D66
 
Thanks Kevin and Kirsle for the replies.

Kirsle worked very well except for some reason, it was not completely sorted. For example, A12 and a few others somehow wound up near the end......

Kevin, the sort works great, but I do have one question. Since a dir tree contains the folders '.' and '..' is there an easy way to eliminate them while doing the sort?

Thanks again!
Jim
 
You can get rid of the . and .. when you read the dir to get the filenames or skip them later.

Code:
my @alf = qw(A1 B5 D66 A100 A3 A2 B5 B3 A22 . ..);

my @sorted = map  {$_->[0]}
             sort {$a->[1] cmp $b->[1] ||
                   $a->[2] <=> $b->[2]}
             map  {m/^([a-z]+)(\d+)$/i; [$_,lc($1),$2]} @alf;

for (@sorted) {
   next if /^\.+$/;[b]#skip . and ..[/b]
   print "$_\n";
}
 
Excellent, Kevin!

Thank you very much.
Jim
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top