You could avoid the temp $i by iterating over the indexes instead. Doing that that just puts you one line more (also presuming this is run under a use 5.010 or higher directive so you have say so that gets it back absolute line count wise). You could also use List::MoreUtils for sort_by, but otherwise I couldn't say anything looks particularly awkward in your code.

use 5.010; use List::MoreUtils qw( sort_by ); my @PCHR = qw( K Q R B N P ); my %pchr = map { $PCHR[$_] => $_ } 0..$#PCHR; my $w1 = 'QRKPNB'; my $w2 = join '', sort_by { $pchr{$_} } split( //, $w1 ); say "$w1 -> $w2";

If you really didn't need @PCHR for anything other than creating the ordering hash you could create %pchr with something like this. Still has a temp but it's lexical to the do block, and you can get what was in @PCHR with sort_by {$pchr{$_}} keys %pchr. Really kind of depends what else exactly you're doing which one I'd go with.

my %pchr = do { my $i; map { $_ => $i++ } qw( K Q R B N P ) };

The cake is a lie.
The cake is a lie.
The cake is a lie.


In reply to Re: Sort list by position of items in another list by Fletch
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":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.