in reply to Sort list by position of items in another list

> The Perl code works but compared to the Python version it looks a little bit awkward.

The question is if you want it fast or pretty.

Without extra modules, this doesn't look particular awkward to me.

use strict; use warnings; my $PCHR = "KQRBNP"; my $w1 = "QRKPNB"; my $w2 = join "", sort { index ($PCHR, $a) <=> index ($PCHR, $b) } split //, $w1; print "$w1 -> $w2";

of course it's far more efficient to store the index in a hash, which in turn needs to be precalculated.

Others have shown you external "sort_by" implementations using so-called "key-functions" like in Python ( That's when you can avoid to repeat code for $a and $b).

But I'm not sure if these key-functions - in Python or CPAN - actually cache the results for performance optimization in a hash. (This might be too clever if a key function is supposed to vary results)

Which brings us back to the question: fast or pretty?

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery