in reply to Re^4: top ten things every Perl hacker should know
in thread top ten things every Perl hacker should know
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]};
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^6: top ten things every Perl hacker should know
by qq (Hermit) on Mar 18, 2006 at 20:21 UTC | |
by salva (Canon) on Mar 20, 2006 at 15:55 UTC |