The Schwartzian Transform is a fairly common idiom in Perl and is, to a large extent, using some principles of functional programming (languages such as Lisp or Scheme) in Perl. If Choroba had not done it before, I would have suggested almost the same solution (with probably just some very minor syntactical variations).
To understand such a construct, you have to read it from bottom to top (and sometimes, depending on the exact layout, from right to left).
To understand it better, you can split it mentally into three separate instructions:
my @temp_array = map [ $_, join q(), /[aeiou]/g ], @words;
@temp_array = sort { $a->[1] cmp $b->[1] } @temp_array;
say for map $_->[0], @temp_array;
The first instruction creates a temporary array of array references whose content will be something like this:
(["fanfare", "aae"], [apparate, "aaae"], etc.)
The second instruction will sort the array references in accordance with the second field of each array ref (i.e. the vowels). At the end of this, the temporary array contains the array refs sorted according to the vowels.
The final step is to print out the original words (stripped of the data added in the first step), which will be now sorted according to the vowels.
This process is sometimes referred to as : "decorate, sort, undecorate", because it is adding new data to the original one to enable the sort to work efficiently, and then removes the added data.
Now, the beauty of the Schwartzian Transform is that you don't really need the temporary array: you can just pipeline the data from one step to the next. So if you look back at the code suggested by choroba, the map at the bottom creates a list of array references which are fueled into the sort line above, which sorts in accordance with what the map at the bottom has added to the data, and the result of the sort is fed into the map of the first line, which removes what the first map had added and returns the original list duly sorted in accordance to the vowels of each word.
I hope this helps understanding this slightly advanced construct. Once understood, it becomes very natural to use it.
|