I need to sort an array of arrays; the .sort
method seems to work by
default. But what is a good way to sort by different indices of the
inner arrays?
The array to be sorted is outer larger array: (birthday in 'mmddyy' format)
my @allRecords = [ [birthday1 firstName1 lastName1 [data1]
[birthday2 firstName2 lastName2 [data2]
...
[birthdayN firstNameN lastNameN [dataN] ];
@allRecords.sort by itself sorts by birthdays.
What is a better way to sort by firstName or lastName or by data inside the inner arrays?
The
sort
method takes a sub as optional argument. If its arity is 1, it uses the return value as comparison operands; if its arity is 2, you can manually do the comparison between elements however you see fit by returning one ofLess
,Same
orMore
.Given your example, we can sort by first name like this:
We can sort by last name, then first name, then birthday by doing the separate comparisons explicitly like this:
or again implicitly by transforming the operands:
Transforming the birthday entry so we sort by year first is left as an exercise for the reader, but one way to do it would be to add something like
where appropriate.