Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

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);
like image 269
yegor256 Avatar asked Nov 22 '25 15:11

yegor256


1 Answers

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
like image 172
Steffen Ullrich Avatar answered Nov 24 '25 10:11

Steffen Ullrich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!