Search code examples
perl

How to insert an element into array shifting all others right?


I have an array, and I want to insert a new element inside it, shifting all other elements to the right:

my @a = (2, 5, 4, 8, 1);
# insert 42 into position no. 2

Result expected:

(2, 5, 42, 4, 8, 1);

Solution

  • my @a = (2, 5, 4, 8, 1);
    splice(@a, 2, 0, 42);   # -> (2, 5, 42, 4, 8, 1)
    

    This means: in array @a position 2 remove 0 elements and add the element 42 (there can be more elements added). For more see splice, specifically this usage:

    splice ARRAY or EXPR,OFFSET,LENGTH,LIST