1. Perl
  2. builtin functions
  3. here

splice function - complex manipulation of array elements

The splice function allows you to perform complex operations on the elements of arrays. You can retrieve and replace multiple elements.

Extraction of multiple elements

You can retrieve multiple elements of an array in the following ways:

# Extraction of multiple elements
@parts = splice @array, $pos, $length;

$pos specifies the start position of retrieval. For $length, specify the length to retrieve. If $length is omitted when fetching multiple elements, the target is from the position of $pos to the end of the array.

Replacement of multiple elements

By specifying an array in the 4th argument, you can replace with the specified array. The target array has the same syntax as above.

# Multi-element replacement
splice @array, $pos, $length, @replace;

How to use the splice function

First of all, shift function, unshift function, pop function and push function Please consider it. 90%of programs can be written using these four functions.

Then use the splice function when complex operations are required.

Example program

This is an example program that extracts multiple elements. (2,3) is assigned to @parts and @nums becomes (1, 4).

# Extraction of multiple elements
my @nums = (1, 2, 3, 4);
my @parts = splice @nums, 1, 2;

This is an example that replaces multiple elements. @nums becomes (1, 5, 6, 4).

# Multi-element replacement
my @nums = (1, 2, 3, 4);
my @replace = (5, 6);
splice @nums, 1, 2, @replace;

Related Informatrion