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

sort on numeric portion of key 1

Status
Not open for further replies.

adumitrescu

Programmer
Jun 15, 2005
18
CA
Hello,
The items in my array all looks like "nnn/xxx" where nnn is a number with 1 to 5 digits, and xxx is a string. I wish to sort this array numerically. Using sort {$a <=> $b} %array does sort as desired, but outputs a TON of warnings about my argument not being numeric. I don't want to just hide the warnings - I would rather tune my sort comparison to be more intelligent (only compare the piece up to but not including the slash.
Thanks.
 
First of all, %array is not an array but a hash. I'm assuing that you either want "keys %hash" or "@array". I'll let you decide which is appropriate.

Secondly, all you need to do is a Schwartzian transform:

Here is an example that does what you require:

Code:
my @array = ('5/aaa', '12/bbb', '4/ccc');

my @sorted = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [$_, m/(\d+)/] } @array;

# Equals: 4/ccc,5/aaa,12/bbb
 
Thanks MillerH,
This does exactly as I had hoped - awesome!

p.s. Sorry for the misunderstanding - My old Perl book doesn't use the term 'hash' for %array, but rather Associative Array.

Cheers - The Foreign Kid
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top