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

Dear Monks

I have an array

my @OldArray=(0..50);

I need to move few index into another new array

my @NewArray = @OldArray[1..25];

I know how to copy index from array to array. But, how to move one array index into another array

Please advice me!

Thanks
Rose

Replies are listed 'Best First'.
Re: Array index move into another array
by FunkyMonk (Bishop) on Apr 17, 2009 at 12:57 UTC
    When you say index, I think you mean element (I hope). In which case splice is the function you need:
    my @old_array = 1..5; my @new_array = splice @old_array, 2, 2;

    leaves @old_array containing (1, 2, 5) and @new_array has (3, 4).

      This is what I expected.

      Thanks a lot !!

Re: Array index move into another array
by targetsmart (Curate) on Apr 17, 2009 at 12:52 UTC
    I know how to copy index from array to array. But, how to move one array index into another array
    basically move is a copy+remove operation
    so you can copy(like what you shown), then you can delete

    NOTE
    Also, deleting array elements in the middle of an array will not shift the index of the elements after them down. Use splice for that.


    Vivek
    -- In accordance with the prarabdha of each, the One whose function it is to ordain makes each to act. What will not happen will never happen, whatever effort one may put forth. And what will happen will not fail to happen, however much one may seek to prevent it. This is certain. The part of wisdom therefore is to stay quiet.
Re: Array index move into another array
by johngg (Canon) on Apr 17, 2009 at 16:36 UTC

    Just to expand a little on FunkyMonk's answer, using a list as a fourth et seq. argument to splice allows you to insert elements into an array. The following silly example, spliceing the heron and parrot out of @mammals and into @birds, gives you the general idea.

    use strict; use warnings; my @mammals = qw{ cat dog heron parrot stoat zebra }; my @birds = qw{ coot sparrow }; print qq{Before:\n @mammals\n @birds\n}; splice @birds, 1, 0, splice @mammals, 2, 2; print qq{ After:\n @mammals\n @birds\n};

    The output.

    Before: cat dog heron parrot stoat zebra coot sparrow After: cat dog stoat zebra coot heron parrot sparrow

    I hope this is of interest.

    Cheers,

    JohnGG

    Update: AnomalousMonk pointed out that I really needed a "Before" and "After" rather than two "Before"s. That's what comes of careless cut 'n' paste development :-(

Re: Array index move into another array
by cdarke (Prior) on Apr 17, 2009 at 12:52 UTC
    If I understand your question correctly:
    use strict; use warnings; my @OldArray=(0..50); my @NewArray; @NewArray[1..25] = @OldArray[1..25];