Removing Element from an Array

Let's learn how to remove elements from an array in this lesson.

Removing element from the start

To remove an element from the start of the array, we use the shift() subroutine.

shift() deletes the element located at index 0 of the array. All numerical array keys will be modified to start counting from 0.

shift() subroutine takes only one parameter, i.e., the name of the array. It deletes the element located at index 0 and shifts the remaining elements towards the start of the array. You can call this function multiple times if you want to delete more than one entry from the beginning of an array.

The following is an example of removing elements from the start of an array:

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

Press + to interact
@myArray = (0, 1, 2, 3);
print("Original: @myArray\n\n");
shift(@myArray);
print("After removing 0 from the array: @myArray");

Removing element at the end

To remove the last element of an array, we use the pop() subroutine.

The pop() subroutine removes the last element of an array. All numerical array keys will remain the same.

pop() takes one parameter, i.e., the name of the array. It deletes the last element of the array. You can call this subroutine multiple times if you wish to delete multiple elements from the end of an array.

The following example visualizes the working of the pop() subroutine:

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

Press + to interact
@myArray = (0, 1, 2, 3);
print("Original: @myArray\n\n");
pop(@myArray); # removing 3 from the end of $array
print("Removing 3 from the end of the array: @myArray");

Removing element from a specific index

To remove an element from a specific index of an array, we can use the undef statement. The undef statement is followed by the array name with the index to remove, as shown below. The specific array location will become empty as a result of execution of the undef statement:

@myArray = (0, 1, 2, 3);
undef $myArray[1]; 

Now, if we try to access the $myarray[1], it gives us nothing because this index of the array has no value. Let’s have a look at this example:

Press + to interact
@myArray = (0, 1, 2, 3);
print "@myArray \n";
undef $myArray[1];
print("After removing 1st element from the array: @myArray");