hotshot has asked for the wisdom of the Perl Monks concerning the following question:

is there a short way to move an element in an array. my function gets as arguments indexFrom and indexTo and I want to move the indexFrom entry to indexTo and ordering the array as necessary, for example:
my @array = qw(one two three four five six seven); @newArray = myFunc(\@array, 4, 1); print join(', ', @newArray); # should give us: one, five, two, three, four, six, seven
as we can see the entry move to the desired location and the rest of the array shifted a little (BTW, the entry can move forward also).

Thanks

Hotshot

Replies are listed 'Best First'.
Re: switching array entries
by zigdon (Deacon) on Oct 30, 2002 at 14:08 UTC

    You're probably looking for the splice function:

    my @array = qw(one two three four five six seven); splice(@array,1,0,$array[4]); # add the item to the new position splice(@array,5,1); # remove it from it's old position (note the moved + index) print "@array"'

    There's probably a cool way to do this in one shot.

    Update: and there is a cool way to do it! see mce's reply.

    -- Dan

Re: switching array entries
by mce (Curate) on Oct 30, 2002 at 14:14 UTC
    Hi, ++zigdon,
    You can even do it on one go.
    splice(@array,1,0,splice(@array,4,1) );

    cool he,
    ---------------------------
    Dr. Mark Ceulemans
    Senior Consultant
    IT Masters, Belgium
      thanks for your answer, but pay attentions that if $indexFrom is smaller than $indexTo, we have to susbstruct 1 in the the outer splice's offset.

      Hotshot
Re: switching array entries
by robartes (Priest) on Oct 30, 2002 at 14:33 UTC
    Or, in yet another way to do it, and assuming variable indexTo means the index position before the move (i.e. indexTo=4 means in front of the element that was the element with index 4 before the move):
    splice(@array,$indexTo-($indexTo>$indexFrom),0,splice(@array,$indexFro +m,1));

    CU
    Robartes-

Re: switching array entries
by artist (Parson) on Oct 30, 2002 at 15:23 UTC

    I looked at two different approach:

    $p1 = 1; $p2 = 4;

    splice(@array,$p1+1,0,splice(@array,$p1,$p2-1));
    AND
    splice(@array,$p1,0,splice(@array,$p2,$p1) );
    The second approach involves less 'moving'.

    Artist