Schwartzian transform no relation reference to an anonymous 2-element array
the original list @unsorted is fed into a map operation that wraps each item into a (reference to an anonymous 2-element) array consisting of itself and the calculated value that will determine its sort order (list of item becomes a list of [item, value]);
then the list of lists produced by map is fed into sort, which sorts it according to the values previously calculated (list of [item, value] ⇒ sorted list of [item, value]);
finally, another map operation unwraps the values (from the anonymous array) used for the sorting, producing the items of the original list in the sorted order (sorted list of [item, value] ⇒ sorted list of item).The use of anonymous arrays ensures that memory will be reclaimed by the Perl garbage collector immediately after the sorting is done.While it is shorter to code, the naive approach here could be much less efficient if the key function (called foo in the example above) is expensive to compute. This is because the code inside the brackets is evaluated each time two elements need to be compared. An optimal comparison sort performs O(n log n) comparisons (where n is the length of the list), with 2 calls to foo every comparison, resulting in O(n log n) calls to foo. In comparison, using the Schwartzian transform, we only make 1 call to foo per element, at the beginning map stage, for a total of n calls to foo.
However, if the function foo is relatively simple, then the extra overhead of the Schwartzian transform may be unwarranted.
no relation