Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Sort list by position of items in another list

by LanX (Saint)
on Feb 18, 2022 at 22:06 UTC ( [id://11141482]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11141482]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2024-04-23 20:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found