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

Re: How to Order an Array's Elements to Match Another Array's Element Order

by Athanasius (Bishop)
on Sep 17, 2019 at 08:06 UTC ( #11106278=note: print w/replies, xml ) Need Help??


in reply to How to Order an Array's Elements to Match Another Array's Element Order

Hello ozboomer,

Perl’s built-in sort function accepts a custom subroutine to do the comparisons. Here is one using the first_index function from List::MoreUtils:

use strict; use warnings; use Data::Dump; use List::MoreUtils qw( first_index ); my @fruit = qw( APPLE ORANGE PEACH GRAPE BANANA PINEAPPLE ); my @subset = qw( PINEAPPLE GRAPE APPLE ); #my @subset = qw( PINEAPPLE GRAPE PEACH BANANA APPLE ORANGE ); my @results = sort fruit_order @subset; dd \@results; sub fruit_order { (first_index { $a eq $_ } @fruit) <=> (first_index { $b eq $_ } @fruit); }

Output:

18:00 >perl 2017_SoPW.pl ["APPLE", "GRAPE", "PINEAPPLE"] 18:04 >

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2019-12-14 04:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?