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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sorting alphanumeric 1

Status
Not open for further replies.

Alphabin

Programmer
Dec 8, 2002
119
CA
Hi,

I'm trying to sort alphanumeric data. Here's an example of the numbers:
33311a
33311b
33312
33313

Right now I'm using the "cmp" operator but I get the following results:
33312
33313
33311a
33311b

Coding:
Code:
$case{$a}{$num} cmp $case{$b}{$num}

Thanks
 
What order are you expecting them to be sorted in?
 
Try this:
Code:
#!/usr/bin/perl -w
@elems = qw( 33311b 33313 33312 33311a );
sub byNumberPartThenString {
    my $aNum = $a;
    my $bNum = $b;
    $aNum =~ s/\D//g;
    $bNum =~ s/\D//g;
    return ($aNum <=> $bNum) || ($a cmp $b);
}
foreach $elem (sort byNumberPartThenString @elems) {
    print "$elem\n";
}
Cheers, Neil
 
why people insist solving solved probls ?
to do it easy, put your data in a file, say abc
then enter a
sort abc
do you need numerical sort, enter
sort -n abc
a reversed num sort ?
sort -nr abc
an unique reversed numerical?
sort -nru abc
the best unix tool is called 'man'
to use it try: man sort<enter>
remember <enter> means the 'enter' or 'return' key!
 
iribach,

I think the answer to your question is: TIMTOWTDI (There's more than one way to do it).

While sort works, you can always do it other ways to help learn the language and it's different abilities. Toolkit's example is a great way to show how to sort alphanumeric characters using cmp instead of sort.

Try spending a little more time helping people instead of posting rude replies, it makes a difference.

- Rieekan
 
Toolkit
Thank you very much for your help. It's really appreciated. It's working perfectly.

RieekanThank you for your comments.
 
Rieekan
thank you
expecially for TIMTOWTDI, willy sure appreciate it.
sure in unix 20 ways conduces to the same goal
the Q was: why a 20 line code to do a sort?
but sure you are right.
why use a sort when i can do it in a 20 line script.
AGAIN: thhhanks 4 expl of TIMTOWTDI.
DBDGAIK
 
Much will depend on where the data is coming from. Sure, if the data is in a file on a unix-type system and you don't ever need to move your script to another os, using the unix sort command is ideal. However, if the data is coming for elsewhere, it's probably better to avoid the overhead of file I/O, also depending on how much data is in question.

If there are only going to ge a few elements in the array, as in the example, using a file and the unix sort command is overkill.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top