Adding Elements in an Array

Adding elements at the start using unshift()

One or multiple elements can be added at the start of the array using the unshift() subroutine.

unshift() prepends passed elements at the front of an array. Note that the list of elements is prepended as a whole so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from 0.

unshift() has two or more input parameters: the first parameter is the name of the array, and the subsequent parameters are the elements to be added at the start of that array.

The following is an example of adding elements at the start of an array:

Let’s run the following code to see how this works:

Press + to interact
@myArray = (2, 3);
print("Original: @myArray\n\n");
unshift(@myArray, 0, 1);
print("After adding 0 and 1: @myArray");

Adding elements at the end using push()

One or multiple elements can be added at the end of the array using the push() subroutine.

push() subroutine pushes one or more elements at the end of an array. All numerical array keys will remain the same, and new ones will be created corresponding to the new elements pushed.

push() also has two or more input parameters: the first parameter is the name of the array, and the subsequent parameters are the elements to be added at the end of that array.

The following is an example of adding elements at the end of an array:

Let’s run the code snippet below to see how this is done in Perl:

Press + to interact
@array = (1, 2, 3);
print("Original: @array\n\n");
push(@array, 4); # Pushing 4 at the end of $array
push(@array, 5); # Pushing 5 at the end of $array
print("After adding 4 and 5 at the end: @array");

Adding and replacing values at a random position in an array

To add or replace values at any position in an array, we can access the array position using the key and assign a value. This is shown below:

$arrayName[key]=value;
  • If an old key is used to assign a new value, the old value will be replaced.
  • If a new key is used to assign a value, a new key will be created in the array.

The following code widget shows how this is done in Perl:

Press + to interact
@arr = (1,3,5,7,9);
print("Original: @arr\n\n");
@arr[5]=71; # adding a new key and its assocaited value
@arr[2]=22; # replacing an old value at 2nd index
@arr[9] = 30; # adding a new key and its assocaited value
print("After changing values: @arr");

If the index where a new value is inserted exceeds the highest index, empty entries are added between the last element in the array and the new entry being added.