perl function splice

The splice function in Perl is used to remove or replace elements of an array. It can also be used to add elements to an array.

Here is an example of using the splice function:

my @colors = qw(red green blue yellow orange);

# remove and return the second element
my $removed_element = splice @colors, 1, 1;

print "Removed element: $removed_element\n";
print "Array after removal: @colors\n";

# replace two elements starting at index 1 with new elements
splice @colors, 1, 2, qw(purple pink);

print "Array after replacement: @colors\n";

# add elements to the array
splice @colors, 3, 0, qw(white black);

print "Array after insertion: @colors\n";
S‮o‬urce:www.theitroad.com

Output:

Removed element: green
Array after removal: red blue yellow orange
Array after replacement: red purple pink orange
Array after insertion: red purple pink white black orange

In this example, we have an array @colors with five elements. We first use splice to remove the second element (at index 1) and store it in the variable $removed_element. We then print the modified array.

Next, we use splice to replace two elements starting at index 1 with the elements "purple" and "pink". We print the modified array again.

Finally, we use splice to add the elements "white" and "black" to the array starting at index 3. We print the final modified array.