Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Sort list by position of items in another list

by rsFalse (Chaplain)
on Feb 18, 2022 at 16:29 UTC ( #11141471=note: print w/replies, xml ) Need Help??


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

Ye, it looks awkward or longer, because Perl have no such array index function or sort by array index function in its core.

Perl has some string index functions (index and rindex). In your example they may be used instead of hash, e.g. using Schwartzian transform:
my $i = 0; # use constant PCHR => split //, 'KQRBNP'; # my %pchr = map { $_ => $i++ } PCHR; use constant PCHR => 'KQRBNP'; my $w1 = 'QRKPNB'; my $w2 = join '', map $_->[1], sort { $a->[0] <=> $b->[0] } map [ ( index PCHR, $_ ), $_ ], split //, $w1; print "$w1 -> $w2\n";
I'm not sure if it looks less awkward ;)

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:22 UTC
    Interesting idea, thanks!

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2022-08-18 03:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?