# 7.4 The Schwartzian Transform

The intermediate variables between each of these steps were not necessary, except as input to the next step. You can save yourself some brainpower by just stacking all the steps together:

```my @names =
map \$_->,
sort { \$b-> <=> \$a-> }
map [ \$_, ask_monkey_about(\$_) ],
@castaways;```

Because the map and sort operators are right to left, you have to read this construct from the bottom up. Take a list of @castaways, create some arrayrefs by asking the monkey a simple question, sort the list of arrayrefs, and then extract the names from each arrayref. This gives you the list of names in the desired order.

This construct is commonly called the Schwartzian Transform, which was named after me (but not by me), thanks to a Usenet posting I made many years ago. It has proven to be a very nice thing to have in your bag of sorting tricks.

If this transform looks like it might be too complex to memorize or come up with from first principles, it might help to look at the flexible and constant parts:

```my @output_data =
map \$_->,
sort { SORT COMPARISON USING \$a-> AND \$b-> }
map [ \$_, EXPENSIVE FUNCTION OF \$_ ],
@input_data;```

The basic structure maps the original list into a list of arrayrefs, computing the expensive function only once for each; sorts those array refs, looking at the cached value of each expensive function invocation; and then extracts the original values back out in the new order. All you have to do is plug in the proper two operations, and you're done.

 An expensive operation is one that takes a relatively long time or a relatively large amount of memory.   Chapter 1. Introduction  Chapter 2. Building Larger Programs  Chapter 3. Introduction to References  Chapter 4. References and Scoping  Chapter 5. Manipulating Complex Data Structures  Chapter 6. Subroutine References  Chapter 7. Practical Reference Tricks  7.1 Review of Sorting  7.2 Sorting with Indices  7.3 Sorting Efficiently  7.4 The Schwartzian Transform  7.5 Recursively Defined Data  7.6 Building Recursively Defined Data  7.7 Displaying Recursively Defined Data  7.8 Exercises  Chapter 8. Introduction to Objects  Chapter 9. Objects with Data  Chapter 10. Object Destruction  Chapter 11. Some Advanced Object Topics  Chapter 12. Using Modules  Chapter 13. Writing a Distribution  Chapter 14. Essential Testing  Chapter 15. Contributing to CPAN  Appendix A. Answers to Exercises