Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Sort list by position of items in another list

by Fletch (Bishop)
on Feb 18, 2022 at 16:22 UTC ( [id://11141470]=note: print w/replies, xml ) Need Help??


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

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.

Replies are listed 'Best First'.
Re^2: Sort list by position of items in another list
by gflohr (Acolyte) on Feb 18, 2022 at 18:17 UTC
    Yes, List::Util::sort_by makes it look better. Maybe, the Pythonian sorted() could also be an enhancement for List::Util resp. List::MoreUtils.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (7)
As of 2024-04-18 07:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found