Dave's Brain

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.

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.