Perl: the Markov chain saw | |
PerlMonks |
Re: sorting an array of objects (surely it should be easy!)by Fletch (Bishop) |
on Jul 03, 2007 at 13:55 UTC ( [id://624684]=note: print w/replies, xml ) | Need Help?? |
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 . . .
(Of course were this Ruby that'd just be unsorted.sort_by { |x| x.function }; how easily one can get spoiled . . . :)
In Section
Seekers of Perl Wisdom
|
|