Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
> 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


In reply to Re: Sort list by position of items in another list by LanX
in thread Sort list by position of items in another list by gflohr

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (7)
As of 2024-04-19 16:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found