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!

Simple sorting issue

Status
Not open for further replies.

Extension

Programmer
Joined
Nov 3, 2004
Messages
311
Location
CA

I want to sort alphanumeric values like this: 33903A, 33903, 33903C, 33903D.

The values are from an array. I'm using the following:

Code:
sort { $a->[0] cmp $b->[0] }

I'm getting
33903A
33903D
33903D
33903

but I want

33903
33903A
33903D
33903D

Thank you in advance
 
assuming the dats is just like you posted:

Code:
my @array = qw (33903A 33903D 33903D 33903);

my @sorted = map {$_->[0]}
             sort {$a->[1] <=> $b->[1] ||
                   $a->[2] cmp $b->[2]}
             map {/(\d+)(.*)/;[$_,$1,$2]} @array;
print "$_\n" for @sorted;

- Kevin, perl coder unexceptional!
 
Why are you dereferencing a scalar?

Extension said:
sort { $a->[0] cmp $b->[0] }
[/CODE]

The default alpha sorting would already sort the array as you desire.

Code:
my @array = qw(33903A 33903 33903C 33903D);
print join ', ', sort @array;
# Outputs 33903, 33903A, 33903C, 33903D
 
MillerH said:
Why are you dereferencing a scalar?
He's using a Schwartzian Tranform. $a and $b are arrayrefs, from the first "map" that's applied to the array.
 
ishnid said:
He's using a Schwartzian Tranform. $a and $b are arrayrefs, from the first "map" that's applied to the array.

Ishnid:
I was quoted Extension's dereferencing a scalar, not KevinADC's dereferencing an anonymous array reference. I think that in Extension's attempt to get sorting to work the way that he desired, he somehow ended up with code that dereferenced his scalar array elements. This would definitely explain why his sort code was not working as intended.

Nevertheless, thanks for the introduction to the term Schwartzian Transform. I'm always amused when I find there are names for algoritms that I think are just common knowledge. Nice read at
 
MillerH said:
I was quoted Extension's dereferencing a scalar, not KevinADC's dereferencing an anonymous array reference.
My mistake. Thanks for clearing that up.
 
NP Ishnid. Just clarifying to make sure that Extension got the message since you misread me. :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top