If yes, then you've come to the right place. If no, then you've come to the right place (I wouldn't want to loose out on a prospective reader now, would I?). Please read on - you will find this worth your time.
This post aims to dissect the Schwartzian Transform, and explains it through an example. And while doing this, it shows how cool Perl is.
But what is the Schwartzian Transform? - A way to efficiently sort a list of items.
Why the name? - Legend has it that Randal "Merlyn" Schwartz (wiki page) demonstrated a Perlish version of a Lisp idiom to speed up sorting. And since that day, every time you use the word "Schwartzian Transform", somewhere far beyond the distant seas, the Randal smiles.
How does it speed up sorting? - Patience my child. The blooming of a flower is an analog process, revealing each petal gracefully unlike the open-throw-catch-roll-close process of a frog's tongue. (Yummy?)
Why do I need to know it? - Because it's fun.
Will each line be preceded by a question in the bold font? - Not from now on.
Suppose you have an array of salesman objects - @salesmen, each of which consists of the following attributes:
1. name # salesman name 2. base_salary # base salary 3. n_cust_conned # number of customers conned 4. comm_per_sale # commission per sale
And the sub routine which calculates the total salary of the salesman is:
sub get_total_sal { my ($obj) = @_; my $total_salary = $obj->{base_salary} + $obj->{n_cust_conned} * $obj->{comm_per_sale}; return $total_salary; }
If you were told to sort this array based on the total salary, what would be your code snippet which does the sort?
Without prior knowledge of the transform, maybe something like this:
my @sorted_salesmen = sort { $a->get_total_sal() <=> $b->get_total_sal() } @salesmen;
This would do the job. But what limitation does it induce in your code?
Think about it.