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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |