# reorder an array using only swap(ARRAY, X, Y), # given a new set of indices my @array = qw( put these in a different order ); my @order = qw( 1 3 5 4 2 0 ); reorder_swap(\@array, \@order); # expected outcome: # qw( these a order different in put ) sub reorder_swap { my ($a, $o) = @_; my @P = my @R = 0 .. $#$o; for (0 .. $#$o) { next if $P[$$o[$_]] == $_; swap($a, $P[$$o[$_]], $_); (@P[$R[$_],$$o[$_]], @R[$P[$$o[$_]],$_]) = (@P[$$o[$_],$R[$_]], @R[$_,$P[$$o[$_]]]); } } sub swap { my ($a, $x, $y) = @_; @$a[$x,$y] = @$a[$y,$x]; }