Gossamer Forum
Home : General : Perl Programming :

Flexible Sorting

Quote Reply
Flexible Sorting
I have an array of hashrefs which I want to sort according to some key in the hash.

The key can either be "alpha" or "numeric", and I want to sort either ascending or descending.

Now I could do an "if" statement to distinguish the four cases, symbolically something like
Code:
if (numeric and ascending)
sort {$a->{$sort_key} <=> $b->{$sort_key}} @array;

elsif (numeric and descending)
sort {$b->{$sort_key} <=> $a->{$sort_key}} @array;

elseif (alpha and ascending)
sort {$a->{$sort_key} cmp $b->{$sort_key}} @array;

else (i.e. alpha and descending)
sort {$b->{$sort_key} cmp $a->{$sort_key}} @array;

Is there any other, more elegant way to do this (and is it faster)?

Thanks a lot for your help.

Ivan
-----
Iyengar Yoga Resources / GT Plugins