Replacing Array Elements in Perl


Now we are going to introduce one more function called splice(), which has the following syntax −

Syntax

splice @ARRAY, OFFSET [ , LENGTH [ , LIST ] ]

This function will remove the elements of @ARRAY designated by OFFSET and LENGTH, and replaces them with LIST if specified. Finally, it returns the elements removed from the array. Following is the example −

Example

 Live Demo

#!/usr/bin/perl
@nums = (1..20);
print "Before - @nums\n";
splice(@nums, 5, 5, 21..25);
print "After - @nums\n";

Output

This will produce the following result −

Before - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
After - 1 2 3 4 5 21 22 23 24 25 11 12 13 14 15 16 17 18 19 20

Here, the actual replacement begins with the 6th number after that five elements are then replaced from 6 to 10 with the numbers 21, 22, 23, 24 and 25.

Updated on: 29-Nov-2019

368 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements