Want to sort a complex data structure by some element efficiently?
For example, how do you sort an array of strings by their length?
Use the transform:
@sorted = map { $_->[1] }
sort { $a->[0] <=> $b->[0] }
map { [ length $_, $_ ] } @strings;
Confused? Put in temporary arrays, just to see what we're doing.
create a temporary array of anonymous arrays
(0: length of the string, 1: the string)
@temp = map { [ length $_, $_ ] } @strings;
sort by length
@temp = sort { $a->[0] <=> $b->[0] };
grab just the strings and put them in @sorted
@sorted = map { $_->[1] } @temp;
Knowing the context of certain operationsand being able to chain them together is crucial to a deep and idiomatic understanding of Perl.