Beefy Boxes and Bandwidth Generously Provided by pair Networks
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??


in reply to sorting an array of objects (surely it should be easy!)

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 . . . :)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://624684]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (7)
As of 2024-04-19 12:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found