Because $a and $b are assigned items from the list you're sorting, not indexen. You either want to use $a->function and $b->function, or sort a list of indexen (sort { $unsorted[$a]->function ... } 0..$#unsorted).
Also if $unsorted[$idx]->function is expensive (or possibly changes during the course of the sort) you might want to do a schwartzian transform first and just make one set of calls.
Update: Oop, you know if you don't know what sort passes to the sort block you probably don't know what an ST is . . .
@sorted = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [ $_, $_- +>function ] } @unsorted;
(Of course were this Ruby that'd just be unsorted.sort_by { |x| x.function }; how easily one can get spoiled . . . :)
In reply to Re: sorting an array of objects (surely it should be easy!)
by Fletch
in thread sorting an array of objects (surely it should be easy!)
by jfrm
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |