Here is the same code written as a normal sort.my @sorted_files = map {$_->[0]} sort {$b->[1] <=> $a->[1] or $a->[0] cmp $b->[0]} map {[$_, -s]} @files;
Clearly the Schwartzian Transform is more complex. But if you have a list of 1000 files, it's also about 10 times faster. Which is why we learn it.my @sorted_files = sort {-s $b <=> -s $a or $a cmp $b} @files;
Now to explain my Ruby comment. In Ruby, arrays have a sort_by method. So in this example you'd write:
and you've written the more efficient sort with less code than the regular sort. This does not work in Perl first of all because we don't have a sort_by method, and furthermore because Perl doesn't do anything useful when you try to sort array references. (Ruby sorts them lexicographically, with each field sorting in its "natural" way.)sorted_files = files.sort_by {|f| [- test(?s, f), f]};
In reply to Re^5: top ten things every Perl hacker should know
by tilly
in thread top ten things every Perl hacker should know
by apotheon
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |