Programming-Idioms

History of Idiom 28 > diff from v8 to v9

Edit summary for version 9 :

Version 8

2015-08-01, 01:14:55

Version 9

2015-08-01, 01:16:29

Idiom #28 Sort by a property

Sort elements of array-like collection items in ascending order of x.p, where p is a field of type Item of the objects in items.

Idiom #28 Sort by a property

Sort elements of array-like collection items in ascending order of x.p, where p is a field of type Item of the objects in items.

Code
@sorted = sort { $a->{property} cmp $b->{property} } @unsorted;
Code
@items = sort { $a->{p} cmp $b->{p} } @items;
Comments bubble
The sort function is given references to two items in the list to sort $a and $b, so you simply write a predicate to sort the list.
Comments bubble
The sort function is given references to two items in the list to sort $a and $b, so you simply write a predicate to sort the list. The cmp operator sorts lexically (i.e., like strings), while the <=> operator sorts numerically. Swap the positions of $a and $b to sort in the reverse direction.