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!

How to alpha and numeric sort an array 1

Status
Not open for further replies.

J1mbo

Programmer
Dec 12, 2002
93
US
I have an array called @list with these elements:

31 BBB0094
31 BBB0096
20 BBB0094
31 AAA0091
31 AAA0093
10 AAA0091
10 BBB0091
20 AAA0091
20 AAA0092

I cannot figure out a perl way to sort the 1st column numerically while also sorting the second column by:
1) the first 3 alphas
then
2) the remaining numbers numerically

Here is my desired output:
10 AAA0091
10 BBB0091
20 AAA0091
20 AAA0092
20 BBB0094
31 AAA0091
31 AAA0093
31 BBB0094
31 BBB0096

Here is what i do now, using the unix sort command, which seems to work:
open(SORT, "| sort -n >>$final")
print SORT @list;
close SORT;

Any help would be appreciated. thanks,

-jim
 
Here's one way using the Schwartzian transform.
Code:
@data =
    map { $_->[0] }
    sort { $a->[1] <=> $b->[1] or $a->[2] cmp $b->[2] or $a->[3] <=> $b->[3] }
    map { [ $_, /^(\d+)\s+([A-Z]{3})(\d+)$/ ]}
    @data;
if you know how many spaces are between the first column and the second one you can replace the second [tt]map[/tt] statemnt with
[tt]
map { [ $_, unpack 'A2x5A3A*', $_ ]}
[/tt]
and change the red number 5 to the actual number of spaces between columns. [tt]unpack[/tt] will probably run a little faster than the regex.

jaa
 
Actually, i just noticed that if your first column is always two digits then you could simple do
Code:
@data = sort @data;
This will sort the lines 'asciibetically' but if the format is rigid then you will always get the desired output. This method won't work if the first column can contain a single digit or a three digit number, because 8 would come after 10 (since 8 > 1), and 20 would come after 100 (since 2 > 1).
(a single digit is ok if it has a preceeding zero, 02 instead of 2.)

jaa
 
Thanks jaa,

i've seen a few examples of this type of sort, but not a name put to it. I found a few good resources after searching google for &quot;Schwartzian transform&quot;. I will put this to work tonight. thank you very much,

jim
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top