yegor256
yegor256

Reputation: 105073

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);

Upvotes: 3

Views: 742

Answers (3)

The unshift() function in Perl places the given list of elements at the beginning of an array. Thereby shifting all values in the array by right.

@a=(1,2,3,4);

print("the output after unshift operation:",unshift(@a,5,6,7,8));

O/P: The output after unshift operation:

5 6 7 8 1 2 3 4

Upvotes: 1

Polar Bear
Polar Bear

Reputation: 6798

It can be easily done by slicing the array in required position.

use strict;
use warnings;
use feature 'say';

use Data::Dumper;

my @arr = (2, 5, 4, 8, 1);
my $pos = 2;
my $val = 42;

say Dumper(\@arr);

@arr = (@arr[0..$pos-1],$val,@arr[$pos..$#arr]);

say Dumper(\@arr);

Output

$VAR1 = [
          2,
          5,
          4,
          8,
          1
        ];

$VAR1 = [
          2,
          5,
          42,
          4,
          8,
          1
        ];

Upvotes: -1

Steffen Ullrich
Steffen Ullrich

Reputation: 123320

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

Upvotes: 14

Related Questions