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 elementssplice(@arr1, 2, 1, "c");splice(@arr2, 1, 3, (20, 30, 40));# print arrayprint "@arr1\n";print "@arr2";
Explanation
- Lines 2–3: We create arrays
arr1andarr2. - Line 6: We use the
splice()method to remove the element at index2of arrayarr1. It should only replace1element. The replacement should be"c". - Line 7: We use the
splice()method to remove the element at index1of arrayarr2. It should replace3elements. The replacements should be elements20,30, and40. - Lines 9–10: We print the arrays.