Dave's Brain

Browse - programming tips - perl insert into 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.
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2012, 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.
Advertisements: