Browse - Programming Tips - How do I insert an element into a perl array?

Date: 2011aug10
Language: perl

Q.  How do I insert an element into a perl array?

A.  Use splice() with the third parameter (how much to delete) set to zero.

@a = qw(aaa bbb ccc ddd); # To insert 'NEW THING' at position 2: splice(@a, 2, 0, 'NEW THING');
# To duplicate element $index in array @a splice(@a, $index, 0, $a[$index]);
Use push() when you want to add something at the end.