Home > front end >  How to insert an element into array shifting all others right?
How to insert an element into array shifting all others right?

Time:11-26

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

CodePudding user response:

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

CodePudding user response:

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
        ];
  •  Tags:  
  • perl
  • Related