http://www.perlmonks.org?node_id=11106329


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

Here's something completely different - it doesn't use a sort !

#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11106277 use warnings; my @array = ( "APPLE", "ORANGE", "PEACH", # Use this for the O +RDER "GRAPE", "BANANA", "PINEAPPLE" ); my @subset = ( "PINEAPPLE", "GRAPE", "APPLE" ); # A required subset +but NOT # in the required order my %order; @order{ @array } = 0 .. $#array; my @results; @results[ @order{ @subset } ] = @subset; @results = grep defined, @results; print "results: @results\n";

Just kidding, this is called a distribution sort.

  • Comment on Re: How to Order an Array's Elements to Match Another Array's Element Order
  • Download Code

Replies are listed 'Best First'.
Re^2: How to Order an Array's Elements to Match Another Array's Element Order
by LanX (Archbishop) on Sep 18, 2019 at 10:22 UTC

    >

    my @array = ( "APPLE", "ORANGE", "PEACH", # Use this for the +ORDER "GRAPE", "BANANA", "PINEAPPLE" );

    shouldn't this be completely ordered ?

    BANANA < GRAPE < ORANGE

    UPDATE

    never mind, I should've read the OP first! :-)

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery FootballPerl is like chess, only without the dice