How to replace array elements in Perl using the splice() method

Overview

We can use the splice method to remove the elements of an array and replace them with the ones we specify.

Syntax

splice(@array, start, no_of_el, new_el)

Parameters

  • @array: This is the array whose elements we want to replace.

  • start: This is the index position from which to start the replacement.

  • no_of_el: TThis is the number of elements to replace.

  • new_el: This is the new element or elements that will replace the current elements of the array.

Return value

A new array with new elements that replaced the previous ones is returned.

Example

# create arrays
@arr1 = ("a", "b", "d", "d", "e");
@arr2 = (10, 70, 80, 90, 50);
# replace elements
splice(@arr1, 2, 1, "c");
splice(@arr2, 1, 3, (20, 30, 40));
# print array
print "@arr1\n";
print "@arr2";

Explanation

  • Lines 2–3: We create arrays arr1 and arr2.
  • Line 6: We use the splice() method to remove the element at index 2 of array arr1. It should only replace 1 element. The replacement should be "c".
  • Line 7: We use the splice() method to remove the element at index 1 of array arr2. It should replace 3 elements. The replacements should be elements 20, 30, and 40.
  • Lines 9–10: We print the arrays.

Free Resources